| From: | Haoyu Huang <haoyu(dot)huang(dot)68(at)gmail(dot)com> |
|---|---|
| To: | Palak Chaturvedi <chaturvedipalak1911(at)gmail(dot)com> |
| Cc: | Ashutosh Bapat <ashutosh(dot)bapat(dot)oss(at)gmail(dot)com>, Heikki Linnakangas <hlinnaka(at)iki(dot)fi>, Dagfinn Ilmari Mannsåker <ilmari(at)ilmari(dot)org>, Robert Haas <robertmhaas(at)gmail(dot)com>, Andres Freund <andres(at)anarazel(dot)de>, pgsql-hackers <pgsql-hackers(at)postgresql(dot)org> |
| Subject: | Re: Better shared data structure management and resizable shared data structures |
| Date: | 2026-11-24 18:17:08 |
| Message-ID: | CAM1e6U4_CCDpKP3bokPgkrowvEZmXcgHone+zapDmcRJK+gnOg@mail.gmail.com |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-hackers |
Hi Ashutosh and Palak,
Thanks for the careful review, and sorry for the slow reply. I agree with
most of your comments. The attached patch contains the changes we made on
top of the first patch I shared in June. It is easier to share the changes
on top of our earlier patch.
Rollback of an interrupted resize
We also spent effort to make the resize atomic, all or nothing. An error
during the resize will roll back all states, including low/highNBuffers.
However, Shrink and Grow have a small window that is difficult to roll
back. We can support rollback, but it will make the code very complex. I do
not expect failures in this window to happen in practice. I haven't seen
them fail in Lakebase dev/staging at all. To be defensive, I explicitly
made the failure in this window complain loudly. Most of the changes are
moving all elog and emitting the results outside these two windows. The
windows are protected with HOLD_INTERRUPTS();
1.
At a high level, the window in shrink is as follows
HOLD_INTERRUPT
pg_atomic_write_u32(&DSBCtrl->highNBuffers, new_size);
MADV_REMOVE the tail.
Shrink buf table
RESUME_INTERRUPT.
2.
The window in grow is
HOLD_INTERRUPT
Update buckets.
Update low/highNBuffers to the new size.
RESUME_INTERRUPT
3.
When there is no size change, as a defensive measure, we ask all
backends to mprotect with the guardNBuffers. If a previous failed shrink is
due to a timeout during WaitForProcSignal, it will ask all backends to
mprotect again.
Barriers vs. AccessNBuffersLock
You're right that holding a lock across CheckPointBuffers() and the
bgwriter scan would make a shrink wait for a whole checkpoint. It also puts
the cost on every scan rather than on the rare resize. It didn't hurt us
because in our environment the checkpointer doesn't make data pages durable
locally (they're rebuilt from WAL), so BufferSync() is much cheaper than in
stock PostgreSQL.
One thing worth knowing is that the barrier completes on the slowest
backend's next CHECK_FOR_INTERRUPTS(). This is actually the longest wait we
observe in the resize protocol. We hit backends that went minutes without
absorbing a barrier. The most important ones apply upstream too:
-
SyncRepWaitForLSN() runs with interrupts held (it asserts
InterruptHoldoffCount > 0), so a backend waiting for a synchronous standby
doesn't absorb barriers until the standby confirms. With synchronous_commit
= remote_apply and a slow standby, that wait can be long.
-
A backend blocking writes to a client that isn't reading incurs no
barrier, because ProcessClientWriteInterrupt() only acts on a pending die.
That includes sending an ERROR, which PostgresMain() does with interrupts
held.
-
A query cancel or timeout can strand a barrier. ProcessInterrupts()
clears InterruptPending, then throws the cancel ERROR before it reaches the
ProcSignalBarrierPending check. Afterward, ProcSignalBarrierPending is
still set, but InterruptPending isn't, so CHECK_FOR_INTERRUPTS() ignores
the barrier until an unrelated interrupt arrives. A session that sits idle
in a transaction, or keeps hitting a short statement_timeout, can hold a
resize for minutes.
-
A handler that reaches CHECK_FOR_INTERRUPTS() can re-enter
ProcessProcSignalBarrier(), because errfinish() checks for interrupts after
any message below ERROR. If another barrier arrives in the meantime, such
as DROP DATABASE, the nested call writes to the newer generation. That also
acknowledges the resize barrier the outer call hasn't finished applying, so
the resizer moves on too early.
-
A process that never calls ProcSignalInit() doesn't absorb these
barriers, and WaitForProcSignalBarrier() doesn't wait for them. That
includes a background worker that doesn't connect to a database, such as
pg_prewarm's autoprewarm leader, whose apw_dump_now() walks the buffer
descriptors up to NBuffers. Unless I missed where the series handles this,
the leader keeps the pool size it saw at startup, so after a shrink, it
reads descriptors from memory the shrink has freed.
enable_dynamic_shared_buffers
Agreed, it isn't needed upstream. In our service it's a postmaster-level
kill switch that turns off every new code path, which helped us roll the
feature out gradually. Upstream, max_shared_buffers = shared_buffers gives
the same effect.
Checkpointer request queue
Yes, our DSB_CHECKPOINT_REQUESTS is specific to our storage. Sizing the
queue to MaxNBuffers can cost up to 320 MB of shared memory when
max_shared_buffers is large. This is not ideal for lakebase when an
endpoint has a large scaling range and a low minCU, such as 1 GB. Then, 320
MB for the checkpointer queue is simply too large.
SHOW shared_buffers: lowNBuffers vs. highNBuffers
I do not have a strong opinion here.
Naming
Heikki, David, and I also went back and forth on the names. We picked
lowNBuffers and highNBuffers because they are neutral with respect to
growth and shrinkage. Their names are easier to understand and state that
low is always less than or equal to high.
Tests
Agreed, our patch didn't include its tests. They live in our test harness.
Two things worked well there and could be ported to TAP.
The first is a fault counter. A test-only setting injects an ERROR, FATAL,
cancel, or terminate at the Nth step of a resize, and the test runs N times
over every step in both directions. After each run, it asserts that all
states match either the old or the new size. That's how we checked our
rollback paths. With injection points, it could be one helper that walks
the protocol's points, instead of listing them by hand as 001 does now.
The second is long randomized resize runs under SQL fuzzers (sqlsmith,
SQLancer) with fault injection. That's where we observed some of the
barrier absorption stalls above.
Thanks,
Haoyu
On Thu, Aug 13, 2026 at 6:30 AM Palak Chaturvedi <
chaturvedipalak1911(at)gmail(dot)com> wrote:
> Hi Ashutosh,
>
> Thanks for the review, and for the pointer to the simpler sink pattern.
> v20260813 tries to incorporate all four points; details inline below.
> Please let me know if anything reads differently from what you had in
> mind.
>
> Attaching two patches. 0001 is your v20260724-0006 as-is, so the CF
> bot has the full apply target. 0002 is the test_shmem portability
> fix.
>
> On Wed, 12 Aug 2026 at 16:32, Ashutosh Bapat
> <ashutosh(dot)bapat(dot)oss(at)gmail(dot)com> wrote:
> >
> > On Mon, Aug 10, 2026 at 11:07 PM Palak Chaturvedi
> > <chaturvedipalak1911(at)gmail(dot)com> wrote:
> > >
> > > Hi Ashutosh,
> > > Attached is a test-portability fix on top of v20260724-0006 to unblock
> > > CFbot [1], plus the small diagnostic patch I used to root-cause it, in
> > > case it's useful later.
> > >
> > > v20260810-0001 = your v20260724-0006, unchanged, renumbered so
> > > CFbot picks up the set as one series
> > > v20260810-0002 = the proposed fix (test module only; no changes
> > > outside src/test/modules/test_shmem/)
> > > v20260810-0003 = diagnostic elog around the existing smaps walker
> > > (please don't commit this one; it's here so the
> > > same instrumentation can be reused later)
> > >
> > > Also attached:
> > > smaps-trace-64bit.txt full 64-bit trace, 12 pids
> > > smaps-trace-32bit.txt per-pid header + first 8 include lines +
> > > elided marker + stop/result; the full trace
> > > is available by rerunning 0003
> > >
> > > Method
> > > ------
> > >
> > > To root-cause this rather than guess from the CFbot failure messages,
> > > I forked off the CF tip (50911a16240 with v20260724-0006 applied),
> > > added logging only to test_shmem_usage() (0003), pushed to trigger a
> > > GitHub Actions run [2], and read the archived server logs. The green
> > > run of 0001+0002 is at [3] (9 jobs pass: Linux 32, Linux 64, macOS,
> > > Windows MinGW, both Windows VS slices, plus SanityCheck,
> > > CompilerWarnings, Linux Autoconf).
> >
> > Thanks for the investigation and the diagnostic and fix patch.
> >
> > >
> > > Diff summary of 0002 vs your patch:
> > >
> > > src/test/modules/test_shmem/t/002_resizable_shmem_struct.pl | 13
> +++++-
> > > src/test/modules/test_shmem/test_shmem.c | 50
> > > ++++++++--------
> > > 2 files changed, 35 insertions(+), 28 deletions(-)
> > >
> > > Findings
> > > --------
> > >
> > > 1. test_shmem_usage() smaps walker crosses the mapping boundary
> > > ---------------------------------------------------------------
> > >
> > > The walker only checks address contiguity (start == prev_end) between
> > > adjacent VMAs, so the first VMA of any kind that happens to abut the
> > > target /dev/zero (deleted) segment is silently pulled into the RSS
> > > sum. The comment on the loop mentions mprotect() splitting the
> > > mapping, but the check itself is unaware of the split's identity.
> > >
> > > On Linux 64-bit CI, for the "shrink to minimum, session 1" scenario
> > > (one of the smallest overages, +139264 bytes over sum(allocated_size)):
> > >
> > > include target VMA: 7f1b84b0c000-7f1b84de6000 rw-s ... 10315
> > > /dev/zero (deleted) Rss=1116 kB, total=1116 kB
> > > include contiguous VMA: 7f1b84de6000-7f1b9dde5000 ---s ... 10315
> > > /dev/zero (deleted) Rss=0 kB, total=1116 kB
> > > include contiguous VMA: 7f1b9dde5000-7f1b9de00000 rw-s ... 10315
> > > /dev/zero (deleted) Rss=0 kB, total=1116 kB
> > > include contiguous VMA: 7f1b9de00000-7f1b9e600000 rw-p 00000000
> 00:00 0
> > > Rss=2048 kB, total=3164 kB <-- adjacent private anonymous VMA
> > > stop before VMA: 7f1b9e6f7000-7f1b9f200000 rw-p 00000000
> 00:00 0
> > > result: rss=3164 kB swap=0 kB shared_hugetlb=0 kB bytes=3239936
> > >
> > > Reported shmem_usage is 3164 kB; real shared-segment RSS is 1116 kB.
> > > The 2048 kB delta is one adjacent private anonymous VMA that happens
> > > to sit right after the shared segment. Across the 12 failing
> > > accounting scenarios on 64-bit, the same 2048 kB VMA at
> > > 7f1b9de00000-7f1b9e600000 is wrongly included every time, and the
> > > walker's final "bytes=" matches the TAP-reported shmem_usage exactly
> > > (full log in smaps-trace-64bit.txt).
> > >
> > > On 32-bit the same bug is much worse. The walker crosses out of the
> > > target /dev/zero segment, through one anonymous VMA, and then straight
> > > into the writable segments of loaded libraries: libcap-ng, libresolv,
> > > libc, libssl, libcrypto, libm, libicu*, libkrb5*, libldap, liburing,
> > > libxml2, libzstd, libstdc++, libsystemd, libubsan, and several more,
> > > before it finally stops at another SysV shared segment. Per-pid,
> > > roughly 170 adjacent VMAs are wrongly included; overage is about 2 MB
> > > per scenario. Header excerpt for one pid (target=0xd35d9700), full
> > > per-pid summary in smaps-trace-32bit.txt:
> > >
> > > include target VMA: d3325000-d99da000 rw-s 00000000 00:01 8414
> > > /dev/zero (deleted)
> > > include contiguous VMA: d99da000-ec5d9000 ---s 066b5000 00:01 8414
> > > /dev/zero (deleted)
> > > include contiguous VMA: ec5d9000-ec5f3000 rw-s 192b4000 00:01 8414
> > > /dev/zero (deleted)
> > > include contiguous VMA: ec5f3000-ec5f9000 rw-p 00000000 00:00 0
> > > include contiguous VMA: ec5f9000-ec5fa000 r--p ...
> > > /usr/lib/i386-linux-gnu/libcap-ng.so.0.0.0
> > > ...
> > > ... (168 more contiguous VMAs elided) ...
> > > stop before VMA: f02dc000-f02dd000 rw-s ... /SYSV0088a83c
> (deleted)
> > > result: rss=<garbage, see Finding #2> bytes=109752320
> > >
> > > What 0002 proposes (test_shmem.c): also check permissions[3] (the 's'
> > > vs 'p' character) when continuing across a split. This still handles
> > > the case the loop comment cares about, one MAP_SHARED region split by
> > > mprotect() into a chain of 'rw-s' / '---s' / 'rw-s' adjacent VMAs
> > > backed by the same inode, while excluding adjacent private mappings.
> > >
> > > One thing I'd like your opinion on: the 's' check by itself is not
> > > airtight. If a *different* MAP_SHARED mapping (different inode /
> > > pathname) happened to sit immediately contiguous to our target
> > > segment, the walker would still include it. I haven't hit this on the
> > > CI runners we tested, but on more crowded address spaces (a backend
> > > that has attached to additional SysV segments, for example) it seems
> > > plausible. One option would be to also match on the inode+pathname of
> > > the target VMA (parse them from the same sscanf) and stop as soon as
> > > they change. That's a bit more parsing, not much. Happy to add it to
> > > 0002 or leave it as a follow-up, whichever you'd prefer.
> >
> > Yes, we should check both the shared permissions as well as the pathname.
> >
>
> Done in v20260813-0002. The walker now records the shared/private
> flag, inode, and pathname from the target VMA on first hit, and stops
> as soon as any of those three (or the address contiguity) changes.
> sscanf widened to
>
> "%lx-%lx %7s %lx %15s %lu %*[ \t]%255[^\n]"
>
> so pathnames with spaces (SysV shm "/SYSV... (deleted)") are read
> whole. Anonymous mappings still match because both target_path and
> path init to "".
>
> > >
> > > 2. sscanf("%ld", int64 *) is a width mismatch on MSVC and 32-bit Linux
> > > ----------------------------------------------------------------------
> > >
> > > The CF-base test_shmem_usage() has:
> > >
> > > int64 val;
> > > ...
> > > if (sscanf(line, "Rss: %ld kB", &val) == 1)
> > > total_rss_kb += val;
> > >
> > > sscanf("%ld", ...) writes a sizeof(long) value, but val is int64. On
> > > platforms where long is 32 bits (MSVC on any target, 32-bit Linux),
> > > sscanf writes only the low 32 bits and leaves the upper 32 bits of
> > > val uninitialized. This is what makes the totals in the 32-bit trace
> > > look like garbage: 0003 uses INT64_FORMAT and prints val correctly,
> > > so what you see is the CF-base sscanf's half-populated int64.
> > >
> > > The returned bytes= is still correct because total_rss_kb passes
> > > through mul_size()/add_size() (unsigned Size, which is 32 bits on
> > > 32-bit Linux) and the upper garbage gets truncated. So the accounting
> > > failure isn't hidden -- the delta that TAP compares is right, only
> > > the diagnostic printout looks wrong.
> > >
> > > 0002 switches the four accounting variables (total_rss_kb,
> > > total_swap_kb, total_shared_hugetlb_kb, val) from int64 to plain
> > > 'long', which matches %ld on every supported platform and is more
> > > than wide enough for kB-per-VMA counts.
> >
> > WFM.
> >
>
> Thanks.
>
> > >
> > > 3. read-past-current-size test: compiler elides the read loop
> > > -------------------------------------------------------------
> > >
> > > The read side of resizable_shmem_access_beyond_size() had:
> > >
> > > for (int i = resizable_shmem->num_entries; i < test_max_entries; i++)
> > > sink = resizable_shmem->data[i];
> > >
> > > At -O2 the compiler can legally elide most of that loop: 'sink' is a
> > > plain static int32, resizable_shmem->data is a non-volatile pointer,
> > > and only the last store to sink is externally observable. The CF-base
> > > comment ("Return the last read value so that compiler doesn't optimize
> > > away the assignment to sink") predicts the risk but doesn't prevent
> > > it -- returning sink from the SQL function only pins the last
> > > iteration.
> > >
> > > When the read is elided, the backend never faults, so tests 45-47
> > > fail like this (base + 0003 diagnostic run on Linux 64-bit):
> > >
> > > not ok 45 - read past current size crashes the backend
> > > not ok 46 - read crash reports lost connection
> > > got: '' (empty stderr -- backend didn't crash)
> > > not ok 47 - read succeeds after crash recovery
> > > got: 'f' expected: 't' (no crash, so no recovery)
> > >
> > > 0002 fixes this by casting through a volatile pointer:
> > >
> > > volatile int32 *volatile_data = resizable_shmem->data;
> > > for (int i = resizable_shmem->num_entries; i < test_max_entries; i++)
> > > sink = volatile_data[i];
> > >
> > > Each volatile_data[i] load is now a required side-effect and can't be
> > > elided, so the read actually faults.
> >
> > this looks fine however, I think there is a simpler way. Perform a
> > bitwise operation on each value something like sink &=
> > resizable->data[i], which can't be optimized away and return sink.
> >
>
> Agreed the older int32 sink was too easy for the compiler to drop. I
> went with a slightly different phrasing that has the same effect:
>
> volatile int32 *volatile_data = resizable_shmem->data;
> for (int i = ...; i < ...; i++)
> sink = volatile_data[i];
>
> The volatile qualifier on the pointer forces the compiler to issue
> every load in order, which is what we actually need to reliably hit
> the guard page. If you prefer the &= form for consistency with other
> places in the tree, I'm happy to switch; the two produce identical
> behaviour for this test.
>
>
> > >
> > > 4. Windows: skip 002_resizable_shmem_struct.pl
> > > ----------------------------------------------
> > >
> > > Resizable shared memory isn't supported on Windows yet, and the test
> > > relies on /proc/self/smaps, which is Linux-only. 0002 adds an early
> > > `plan skip_all => 'resizable shared memory tests are not supported on
> > > Windows'` so the two Windows CFbot jobs stop failing. If a future
> > > revision brings Windows support, we can drop the skip.
> >
> > The tests should not run on windows because they are gated on
> > $have_resizable_shmem. Is that not enough? Other than Windows, we do
> > not support resizable shmem on platforms which do not support required
> > MADV flags. The SKIP check you have added won't work in that case.
> >
>
> The internal $have_resizable_shmem gate does cover Linux-without-MADV
> correctly. The reason v20260813-0002 still adds an outer skip is that
> check_shmem_size_gucs() runs before run_resizable_tests(), and inside
> it we shell out to `postgres -C` for shared_memory_initial_size /
> minimum / maximum. On the Windows CFbot runner that invocation
> returns empty stdout (the runner process has an Administrator group
> in its token, and postgres refuses to run in that state). The Perl
> side then does `0 + ""` under `use warnings FATAL`, which is a fatal
> error.
>
> That is exactly the failure in CFbot run 31257091059:
>
> # die: Argument "" isn't numeric in addition (+) at
> # .../002_resizable_shmem_struct.pl line 219.
>
> Line 219 is `0 + $get->('shared_memory_initial_size')` inside
> check_shmem_size_gucs, which is called on line 292 before
> run_resizable_tests(). The $have_resizable_shmem gate is downstream
> of the failure, so it cannot help there.
>
> The outer skip in v20260813-0002 is a runtime `SHOW have_resizable_shmem`
> against a small throwaway cluster, so:
>
> - On Linux-without-MADV the GUC also reads 'off' and the skip fires,
> which is fine because your internal gate would have skipped the
> resize-specific tests anyway; the outer skip only additionally
> avoids running the postgres -C invocations that are portable-safe
> on Linux but not necessary.
> - On Windows the outer skip prevents the check_shmem_size_gucs line
> 219 death.
> - On any future platform where the GUC reads 'off' for a reason we
> haven't thought of, the whole file skips gracefully instead of
> dying at some later postgres -C or ALTER SYSTEM step.
>
> Happy to make changes if you have any suggestions.
>
> > I think we should add a DEBUG elog to print the VMA line at least.
> > Please include it in 0002.
>
> Done. test_shmem_usage() now emits
>
> DEBUG1: test_shmem smaps includes target VMA: <smaps line>
> DEBUG1: test_shmem smaps includes contiguous VMA: <smaps line>
>
> Verification:
> - git am v20260813-0001 and v20260813-0002 on postgres/master at
> 4e68b7e291d: both apply clean.
> - meson test --suite test_shmem: 106 of 106 subtests pass locally.
> - Fork CI on the combined tree:
> https://github.com/palak-chaturvedi/postgres/actions/runs/31685413262.
>
> Thanks,
> Palak
>
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Zsolt Parragi | 2026-11-24 18:35:21 | Event triggers and the commands embedded in CREATE SCHEMA |
| Previous Message | Álvaro Herrera | 2026-11-24 18:08:41 | Re: Resetting snapshots during the first phase of [CREATE |RE]INDEX CONCURRENTLY |