Checkpointer write combining
Checkpointer write combining
Hi, The attached patchset implements checkpointer write combining -- which makes immediate checkpoints at least 20% faster in my tests. Checkpointer achieves higher write throughput and higher write IOPs with the patch. Besides the immediate performance gain with the patchset, we will eventually need all writers to do write combining if we want to use direct IO. Additionally, I think the general shape I refactored BufferSync() into will be useful for AIO-ifying checkpointer. The patch set has preliminary patches (0001-0004) that implement eager flushing and write combining for bulkwrites (like COPY FROM). The functions used to flush a batch of writes for bulkwrites (see 0004) are reused for the checkpointer. The eager flushing component of this patch set has been discussed elsewhere [1]. 0005 implements a fix for XLogNeedsFlush() when called by checkpointer during an end-of-crash-recovery checkpoint. I've already started another thread about this [2], but the patch is required for the patch set to pass tests. One outstanding action item is to test to see if there are any benefits to spread checkpoints. More on how I measured the performance benefit to immediate checkpoints: I tuned checkpoint_completion_target, checkpoint_timeout, and min and max_wal_size to ensure no other checkpoints were initiated. With 16 GB shared buffers and io_combine_limit 128, I created a 15 GB table. To get consistent results, I used pg_prewarm to read the table into shared buffers, issued a checkpoint, then used Bilal's patch [3] to mark all the buffers as dirty again and issue another checkpoint. On a fast local SSD, this proved to be a consistent 20%+ speed up (~6.5 seconds to ~5 seconds). - Melanie [1] https://www.postgresql.org/message-id/CAAKRu_Yjn4mvN9NBxtmsCQSGwup45CoA4e05nhR7ADP-v0WCig@mail.gmail.com [2] https://www.postgresql.org/message-id/CAAKRu_a1vZRZRWO3_jv_X13RYoqLRVipGO0237g5PKzPa2YX6g%40mail.gmail.com [3] https://www.postgresql.org/message-id/flat/CAN55FZ0h_YoSqqutxV6DES1RW8ig6wcA8CR9rJk358YRMxZFmw%40mail.gmail.com
Re: Checkpointer write combining
On Tue, Sep 2, 2025 at 5:10 PM Melanie Plageman wrote: > > The attached patchset implements checkpointer write combining -- which > makes immediate checkpoints at least 20% faster in my tests. > Checkpointer achieves higher write throughput and higher write IOPs > with the patch. These needed a rebase. Attached v2. - Melanie
Re: Checkpointer write combining
Hi,
Thank you for working on this!
On Tue, 9 Sept 2025 at 02:44, Melanie Plageman
wrote:
>
> On Tue, Sep 2, 2025 at 5:10 PM Melanie Plageman
> wrote:
> >
> > The attached patchset implements checkpointer write combining -- which
> > makes immediate checkpoints at least 20% faster in my tests.
> > Checkpointer achieves higher write throughput and higher write IOPs
> > with the patch.
I did the same benchmark you did and I found it is %50 faster (16
seconds to 8 seconds).
From 053dd9d15416d76ce4b95044d848f51ba13a2d20 Mon Sep 17 00:00:00 2001
From: Melanie Plageman
Date: Tue, 2 Sep 2025 11:00:44 -0400
Subject: [PATCH v2 1/9] Refactor goto into for loop in GetVictimBuffer()
@@ -731,6 +741,13 @@ StrategyRejectBuffer(BufferAccessStrategy
strategy, BufferDesc *buf, bool from_r
strategy->buffers[strategy->current] != BufferDescriptorGetBuffer(buf))
return false;
+ buf_state = LockBufHdr(buf);
+ lsn = BufferGetLSN(buf);
+ UnlockBufHdr(buf, buf_state);
+
+ if (!XLogNeedsFlush(lsn))
+ return true;
I think this should return false.
I am planning to review the other patches later and this is for the
first patch only.
--
Regards,
Nazir Bilal Yavuz
Microsoft
Re: Checkpointer write combining
On Tue, Sep 9, 2025 at 9:27 AM Nazir Bilal Yavuz wrote: > Thanks for the review! > From 053dd9d15416d76ce4b95044d848f51ba13a2d20 Mon Sep 17 00:00:00 2001 > From: Melanie Plageman > Date: Tue, 2 Sep 2025 11:00:44 -0400 > Subject: [PATCH v2 1/9] Refactor goto into for loop in GetVictimBuffer() > > @@ -731,6 +741,13 @@ StrategyRejectBuffer(BufferAccessStrategy > strategy, BufferDesc *buf, bool from_r > strategy->buffers[strategy->current] != BufferDescriptorGetBuffer(buf)) > return false; > > + buf_state = LockBufHdr(buf); > + lsn = BufferGetLSN(buf); > + UnlockBufHdr(buf, buf_state); > + > + if (!XLogNeedsFlush(lsn)) > + return true; > > I think this should return false. Oops, you're right. v3 attached with that mistake fixed. - Melanie
Re: Checkpointer write combining
On Tue, Sep 9, 2025 at 9:39 AM Melanie Plageman wrote: > > Oops, you're right. v3 attached with that mistake fixed. One more fix and a bit more cleanup in attached v4. - Melanie
Re: Checkpointer write combining
On Tue, Sep 9, 2025 at 11:16 AM Melanie Plageman wrote: > > One more fix and a bit more cleanup in attached v4. Okay one more version: I updated the thread on eager flushing the bulkwrite ring [1], and some updates were needed here. - Melanie [1] https://www.postgresql.org/message-id/flat/CAAKRu_Yjn4mvN9NBxtmsCQSGwup45CoA4e05nhR7ADP-v0WCig%40mail.gmail.com
Re: Checkpointer write combining
On Tue, 2025-09-09 at 13:55 -0400, Melanie Plageman wrote: > On Tue, Sep 9, 2025 at 11:16 AM Melanie Plageman > wrote: > > > > One more fix and a bit more cleanup in attached v4. > > Okay one more version: I updated the thread on eager flushing the > bulkwrite ring [1], and some updates were needed here. v5-0005 comments: * Please update the comment above the code change. * The last paragraph in the commit message has a typo: "potentially update the local copy of min recovery point, when xlog inserts are *not* allowed", right? * Shouldn't the code be consistent between XLogNeedsFlush() and XLogFlush()? The latter only checks for !XLogInsertAllowed(), whereas the former also checks for RecoveryInProgress(). I'm still not sure I understand the problem situation this is fixing, but that's being discussed in another thread. Regards, Jeff Davis
Re: Checkpointer write combining
On Sep 10, 2025, at 01:55, Melanie Plageman <melanieplageman@gmail.com> wrote:
[1] https://www.postgresql.org/message-id/flat/CAAKRu_Yjn4mvN9NBxtmsCQSGwup45CoA4e05nhR7ADP-v0WCig%40mail.gmail.com
<v5-0004-Write-combining-for-BAS_BULKWRITE.patch><v5-0001-Refactor-goto-into-for-loop-in-GetVictimBuffer.patch><v5-0005-Fix-XLogNeedsFlush-for-checkpointer.patch><v5-0002-Split-FlushBuffer-into-two-parts.patch><v5-0003-Eagerly-flush-bulkwrite-strategy-ring.patch><v5-0006-Add-database-Oid-to-CkptSortItem.patch><v5-0007-Implement-checkpointer-data-write-combining.patch>
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: Checkpointer write combining
On Wed, Sep 10, 2025 at 4:24 AM Chao Li wrote:
>
Thanks for the review!
For any of your feedback that I simply implemented, I omitted an
inline comment about it. Those changes are included in the attached
v6. My inline replies below are only for feedback requiring more
discussion.
> On Sep 10, 2025, at 01:55, Melanie Plageman wrote:
>
> 2 - 0001
> ```
> --- a/src/backend/storage/buffer/freelist.c
> +++ b/src/backend/storage/buffer/freelist.c
>
> + if (XLogNeedsFlush(lsn))
> + {
> + /*
> + * Remove the dirty buffer from the ring; necessary to prevent an
> + * infinite loop if all ring members are dirty.
> + */
> + strategy->buffers[strategy->current] = InvalidBuffer;
> + return true;
> + }
>
> - return true;
> + return false;
> }
> ```
>
> We can do:
> ```
> If (!XLogNeedsFlush(lan))
> Return false
>
> /* Remove the dirty buffer ….
> */
> Return true;
> }
> ```
This would make the order of evaluation the same as master but I
actually prefer it this way because then we only take the buffer
header spinlock if there is a chance we will reject the buffer (e.g.
we don't need to examine it for strategies except BAS_BULKREAD)
> 4 - 0002
> ```
> - /* OK, do the I/O */
> - FlushBuffer(buf_hdr, NULL, IOOBJECT_RELATION, io_context);
> - LWLockRelease(content_lock);
> -
> - ScheduleBufferTagForWriteback(&BackendWritebackContext, io_context,
> - &buf_hdr->tag);
> + CleanVictimBuffer(buf_hdr, &buf_state, from_ring, io_context);
> ```
> I saw CleanVictimBuffer() will get content_lock from bufdesc and release it, but it makes the code hard to understand. Readers might be confused that why content_lock is not released after CleanVictimBuffer() without further reading CleanVictimBuffer().
>
> I’d suggest pass content_lock to CleanVictimBuffer() as a parameter, which gives a clear hint that CleanVictimBuffer() will release the lock.
I think for this specific patch in the set your idea makes sense.
However, in the later patch to do write combining, I release the
content locks for the batch in CompleteWriteBatchIO() and having the
start buffer's lock separate as a parameter would force me to have a
special case handling this.
I've added a comment to both CleanVictimBuffer() and its caller
specifying that the lock must be held and that it will be released
inside CleanVictimBuffer.
> 5 - 0002
> ```
> * disastrous system-wide consequences. To make sure that can't happen,
> * skip the flush if the buffer isn't permanent.
> */
> - if (buf_state & BM_PERMANENT)
> - XLogFlush(recptr);
> + if (!XLogRecPtrIsInvalid(buffer_lsn))
> + XLogFlush(buffer_lsn);
> ```
>
> Why this check is changed? Should the comment be updated accordingly as it says “if the buffer isn’t permanent”, which reflects to the old code.
It's changed because I split the logic for flushing to that LSN and
determining the LSN across the Prepare and Do functions. This is
needed because when we do batches, we want to flush to the max LSN
across all buffers in the batch.
I check if the buffer is BM_PERMANENT in PrepareFlushBuffer(). You
make a good point about my comment, though. I've moved it to
PrepareFlushBuffer() and updated it.
> 8 - 0003
> ```
> bool
> +strategy_supports_eager_flush(BufferAccessStrategy strategy)
> ```
>
> This function is only used in bufmgr.c, can we move it there and make it static?
BufferAccessStrategyData is opaque to bufmgr.c. Only freelist.c can
access it. I agree it is gross that I have these helpers and functions
that would otherwise be static, though.
> 10 - 0004
> ```
> --- a/src/backend/storage/buffer/bufmgr.c
> +++ b/src/backend/storage/buffer/bufmgr.c
>
> + limit = Min(max_batch_size, limit);
> ```
>
> Do we need to check max_batch_size should be less than (MAX_IO_COMBINE_LIMIT-1)? Because BufWriteBatch.bufdescs is defined with length of MAX_IO_COMBINE_LIMIT, and the first place has been used to store “start”.
I assert that in StrategyMaxWriteBatchSize(). io_combine_limit is not
allowed to exceed MAX_IO_COMBINE_LIMIT, so it shouldn't happen anyway,
since we are capping ourselves at io_combine_limit. Or is that your
point?
> 11 - 0004
> ```
> --- a/src/backend/storage/buffer/bufmgr.c
> +++ b/src/backend/storage/buffer/bufmgr.c
>
> + for (batch->n = 1; batch->n < limit; batch->n++)
> + {
> + Buffer bufnum;
> +
> + if ((bufnum = StrategySweepNextBuffer(strategy)) == InvalidBuffer)
> + break;
> ```
>
> Is sweep next buffer right next to start? If yes, can we assert that? But my guess is no, if my guess is true, then is it possible that bufnum meets start? If that’s true, then we should check next buffer doesn’t equal to start.
Ah, great point. I didn't think about this. Our sweep will always
start right after the start buffer, but then if it goes all the way
around, it will "lap" the start buffer. Because of this and because I
think it is weird to have the sweep variables in the
BufferAccessStrategy object, I've changed my approach in attached v6.
I set sweep_end to be the start block in the batch and then pass
around a sweep cursor variable. Hitting sweep_end is the termination
condition.
> 12 - 0004
> ```
> @@ -4306,19 +4370,22 @@ CleanVictimBuffer(BufferAccessStrategy strategy,
>
> if (from_ring && strategy_supports_eager_flush(strategy))
> {
> + uint32 max_batch_size = max_write_batch_size_for_strategy(strategy);
> ```
>
> I think max_batch_size can be attribute of strategy and set it when creating a strategy, so that we don’t need to calculate in every round of clean.
Actually, the max pin limit can change quite frequently. See
GetAdditionalPinLimit()'s usage in read stream code. If the query is
pinning other buffers in another part of the query, it can change our
limit.
I'm not sure if I should call GetAdditionalPinLImit() for each batch
or for each run of batches (like in StrategyMaxWriteBatchSize()).
Currently, I call it for each batch (in FindFlushAdjacents()). The
read stream calls it pretty frequently (each
read_stream_start_pending_read()). But, in the batch flush case,
nothing could change between batches in a run of batches. So maybe I
should move it up and out and make it per run of batches...
> 13 - 0004
> ```
> +void
> +CompleteWriteBatchIO(BufWriteBatch *batch, IOContext io_context,
> + WritebackContext *wb_context)
> +{
> + ErrorContextCallback errcallback =
> + {
> + .callback = shared_buffer_write_error_callback,
> + .previous = error_context_stack,
> + };
> +
> + error_context_stack = &errcallback;
> + pgBufferUsage.shared_blks_written += batch->n;
> ```
>
> Should we only increase shared_blks_written only after the loop of write-back is done?
On master, FlushBuffer() does it after smgrwrite() (before writeback).
I think pgBufferUsage is mainly used in EXPLAIN (also
pg_stat_statements) which won't be used until the end of the query and
won't be displayed if we error out.
> 14 - 0004
> ```
> --- a/src/backend/storage/buffer/freelist.c
> +++ b/src/backend/storage/buffer/freelist.c
>
> +uint32
> +max_write_batch_size_for_strategy(BufferAccessStrategy strategy)
> ```
>
> I think this function can be moved to bufmgr.c and make it static.
This technically could be moved, but it is a function giving you
information about a strategy which seemed to fit better in freelist.c.
> 18 - 0007
> ```
> --- a/src/backend/storage/buffer/bufmgr.c
> +++ b/src/backend/storage/buffer/bufmgr.c
>
> + max_batch_size = checkpointer_max_batch_size();
> ```
>
> Look like we don’t need to calculate max_batch_size in the for loop.
I don't think it's in the for loop.
- Melanie
Re: Checkpointer write combining
On Sep 12, 2025, at 07:11, Melanie Plageman <melanieplageman@gmail.com> wrote:On Wed, Sep 10, 2025 at 4:24 AM Chao Li <li.evan.chao@gmail.com> wrote:
Thanks for the review!
For any of your feedback that I simply implemented, I omitted an
inline comment about it. Those changes are included in the attached
v6. My inline replies below are only for feedback requiring more
discussion.On Sep 10, 2025, at 01:55, Melanie Plageman <melanieplageman@gmail.com> wrote:
2 - 0001
```
--- a/src/backend/storage/buffer/freelist.c
+++ b/src/backend/storage/buffer/freelist.c
+ if (XLogNeedsFlush(lsn))
+ {
+ /*
+ * Remove the dirty buffer from the ring; necessary to prevent an
+ * infinite loop if all ring members are dirty.
+ */
+ strategy->buffers[strategy->current] = InvalidBuffer;
+ return true;
+ }
- return true;
+ return false;
}
```
We can do:
```
If (!XLogNeedsFlush(lan))
Return false
/* Remove the dirty buffer ….
*/
Return true;
}
```
This would make the order of evaluation the same as master but I
actually prefer it this way because then we only take the buffer
header spinlock if there is a chance we will reject the buffer (e.g.
we don't need to examine it for strategies except BAS_BULKREAD)
10 - 0004
```
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
+ limit = Min(max_batch_size, limit);
```
Do we need to check max_batch_size should be less than (MAX_IO_COMBINE_LIMIT-1)? Because BufWriteBatch.bufdescs is defined with length of MAX_IO_COMBINE_LIMIT, and the first place has been used to store “start”.
I assert that in StrategyMaxWriteBatchSize(). io_combine_limit is not
allowed to exceed MAX_IO_COMBINE_LIMIT, so it shouldn't happen anyway,
since we are capping ourselves at io_combine_limit. Or is that your
point?
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: Checkpointer write combining
On Thu, Sep 11, 2025 at 11:33 PM Chao Li wrote:
>
> I don’t understand why the two versions are different:
>
> if (XLogNeedsFlush(lsn))
> {
> /*
> * Remove the dirty buffer from the ring; necessary to prevent an
> * infinite loop if all ring members are dirty.
> */
> strategy->buffers[strategy->current] = InvalidBuffer;
> return true;
> }
>
> return false;
>
> VS
>
> if (XLogNeedsFlush(lsn))
> return false;
I think you mean
if (!XLogNeedsFlush(lsn))
{
return false;
}
// remove buffer
return true
is the same as
if (XLogNeedsFlush(lsn))
{
//remove dirty buffer
return true
}
return false;
Which is true. I've changed it to be like that.
Attached version 7 is rebased and has some bug fixes.
I also added a bonus batch on the end (0007) that refactors
SyncOneBuffer() to use the CAS loop pattern for pinning the buffer
that Andres introduced in 5e89985928795f243. bgwriter is now the only
user of SyncOneBuffer() and it rejects writing out buffers that are
used, so it seemed like a decent use case for this.
- Melanie
Re: Checkpointer write combining
Hi Milanie,
Thanks for updating the patch set. I review 1-6 and got a few more small comments. I didn’t review 0007 as it’s marked as WIP.
>
> - Melanie
>
1 - 0001
```
--- a/src/include/storage/buf_internals.h
+++ b/src/include/storage/buf_internals.h
@@ -421,6 +421,12 @@ ResourceOwnerForgetBufferIO(ResourceOwner owner, Buffer buffer)
/*
* Internal buffer management routines
*/
+
+
+/* Note: these two macros only work on shared buffers, not local ones! */
```
Nit: here you added two empty lines, I think we need only 1.
2 - 0002
```
+static void
+CleanVictimBuffer(BufferDesc *bufdesc,
+ bool from_ring, IOContext io_context)
+{
- /* Find smgr relation for buffer */
- if (reln == NULL)
- reln = smgropen(BufTagGetRelFileLocator(&buf->tag), INVALID_PROC_NUMBER);
+ XLogRecPtr max_lsn = InvalidXLogRecPtr;
+ LWLock *content_lock;
```
Nit: the empty line after “{“ should be removed.
3 - 0003
```
+/*
+ * Return the next buffer in the ring or InvalidBuffer if the current sweep is
+ * over.
+ */
+Buffer
+StrategySweepNextBuffer(BufferAccessStrategy strategy, int *sweep_cursor)
+{
+ if (++(*sweep_cursor) >= strategy->nbuffers)
+ *sweep_cursor = 0;
+
+ return strategy->buffers[*sweep_cursor];
+}
```
Feels the function comment is a bit confusing, because the function code doesn’t really perform sweep, the function is just a getter. InvalidBuffer just implies the current sweep is over.
Maybe rephrase to something like: “Return the next buffer in the range. If InvalidBuffer is returned, that implies the current sweep is done."
4 - 0003
```
static BufferDesc *
NextStratBufToFlush(BufferAccessStrategy strategy,
Buffer sweep_end,
XLogRecPtr *lsn, int *sweep_cursor)
``
“Strat” is confusing. I think it’s the short version of “Strategy”. As this is a static function, and other function names all have the whole word of “strategy”, why don’t also use the whole word in this function name as well?
5 - 0004
```
+uint32
+StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
+{
+ uint32 max_possible_buffer_limit;
+ uint32 max_write_batch_size;
+ int strategy_pin_limit;
+
+ max_write_batch_size = io_combine_limit;
+
+ strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
+ max_possible_buffer_limit = GetPinLimit();
+
+ max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size);
+ max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size);
+ max_write_batch_size = Max(1, max_write_batch_size);
+ max_write_batch_size = Min(max_write_batch_size, io_combine_limit);
+ Assert(max_write_batch_size < MAX_IO_COMBINE_LIMIT);
+ return max_write_batch_size;
+}
```
This implementation is hard to understand. I tried to simplify it:
```
uint32
StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
{
int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
uint32 max_write_batch_size = Min(GetPinLimit(), (uint32)strategy_pin_limit);
/* Clamp to io_combine_limit and enforce minimum of 1 */
if (max_write_batch_size > io_combine_limit)
max_write_batch_size = io_combine_limit;
if (max_write_batch_size == 0)
max_write_batch_size = 1;
Assert(max_write_batch_size < MAX_IO_COMBINE_LIMIT);
return max_write_batch_size;
}
```
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: Checkpointer write combining
Hi Milanie,
Thanks for updating the patch set. I review 1-6 and got a few more small comments. I didn’t review 0007 as it’s marked as WIP.
>
> - Melanie
> <v7-0001-Refactor-goto-into-for-loop-in-GetVictimBuffer.patch><v7-0002-Split-FlushBuffer-into-two-parts.patch><v7-0003-Eagerly-flush-bulkwrite-strategy-ring.patch><v7-0004-Write-combining-for-BAS_BULKWRITE.patch><v7-0005-Add-database-Oid-to-CkptSortItem.patch><v7-0006-Implement-checkpointer-data-write-combining.patch><v7-0007-WIP-Refactor-SyncOneBuffer-for-bgwriter-only.patch>
1 - 0001
```
--- a/src/include/storage/buf_internals.h
+++ b/src/include/storage/buf_internals.h
@@ -421,6 +421,12 @@ ResourceOwnerForgetBufferIO(ResourceOwner owner, Buffer buffer)
/*
* Internal buffer management routines
*/
+
+
+/* Note: these two macros only work on shared buffers, not local ones! */
```
Nit: here you added two empty lines, I think we need only 1.
2 - 0002
```
+static void
+CleanVictimBuffer(BufferDesc *bufdesc,
+ bool from_ring, IOContext io_context)
+{
- /* Find smgr relation for buffer */
- if (reln == NULL)
- reln = smgropen(BufTagGetRelFileLocator(&buf->tag), INVALID_PROC_NUMBER);
+ XLogRecPtr max_lsn = InvalidXLogRecPtr;
+ LWLock *content_lock;
```
Nit: the empty line after “{“ should be removed.
3 - 0003
```
+/*
+ * Return the next buffer in the ring or InvalidBuffer if the current sweep is
+ * over.
+ */
+Buffer
+StrategySweepNextBuffer(BufferAccessStrategy strategy, int *sweep_cursor)
+{
+ if (++(*sweep_cursor) >= strategy->nbuffers)
+ *sweep_cursor = 0;
+
+ return strategy->buffers[*sweep_cursor];
+}
```
Feels the function comment is a bit confusing, because the function code doesn’t really perform sweep, the function is just a getter. InvalidBuffer just implies the current sweep is over.
Maybe rephrase to something like: “Return the next buffer in the range. If InvalidBuffer is returned, that implies the current sweep is done."
4 - 0003
```
static BufferDesc *
NextStratBufToFlush(BufferAccessStrategy strategy,
Buffer sweep_end,
XLogRecPtr *lsn, int *sweep_cursor)
``
“Strat” is confusing. I think it’s the short version of “Strategy”. As this is a static function, and other function names all have the whole word of “strategy”, why don’t also use the whole word in this function name as well?
5 - 0004
```
+uint32
+StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
+{
+ uint32 max_possible_buffer_limit;
+ uint32 max_write_batch_size;
+ int strategy_pin_limit;
+
+ max_write_batch_size = io_combine_limit;
+
+ strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
+ max_possible_buffer_limit = GetPinLimit();
+
+ max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size);
+ max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size);
+ max_write_batch_size = Max(1, max_write_batch_size);
+ max_write_batch_size = Min(max_write_batch_size, io_combine_limit);
+ Assert(max_write_batch_size < MAX_IO_COMBINE_LIMIT);
+ return max_write_batch_size;
+}
```
This implementation is hard to understand. I tried to simplify it:
```
uint32
StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
{
int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
uint32 max_write_batch_size = Min(GetPinLimit(), (uint32)strategy_pin_limit);
/* Clamp to io_combine_limit and enforce minimum of 1 */
if (max_write_batch_size > io_combine_limit)
max_write_batch_size = io_combine_limit;
if (max_write_batch_size == 0)
max_write_batch_size = 1;
Assert(max_write_batch_size < MAX_IO_COMBINE_LIMIT);
return max_write_batch_size;
}
```
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Hello All,
As per reference to the previous mails, I understood the changes made and had tried to replicate the patches into the source code for the bug fix but it didn't show any significant bug. Also I ran some verification tests for the recent changes related to batched write statistics during checkpoints.Below are my observations and results:Test Setup
PostgreSQL version: 19devel (custom build)
OS: Ubuntu Linux
Port: 55432
Database: postgres
Test tool:
pgbenchDuration: 120 seconds
Command used: pgbench -c 4 -j 4 -T 120 -p 55432 -d postgres
Log Output
After running the workload, I triggered a manual checkpoint and checked the latest log entry:
wrote 1383 buffers (8.4%), wrote 3 SLRU buffers;
write=0.023 s, sync=0.017 s, total=0.071 s;
sync files=8, longest=0.004 s, average=0.003 s;
Observations:
Metric | Value | Source | Interpretation |
Buffers written | 1383 | From log | Consistent with moderate workload |
Checkpoint write time | 0.023 s | From log | Realistic for ~11 MB write |
Checkpoint sync time | 0.017 s | From log | Reasonable |
Total checkpoint time | 0.071 s | From log | ≈ write + sync + small overhead |
CHECKPOINT runtime (psql) | - | - | Fast, confirms idle background activity |
The total time closely matches the sum of write and sync times, with only a small overhead (expected for control file updates).
Checkpoint stats in pg_stat_checkpointer also updated correctly, with no missing or duplicated values.
Expected behavior observed:
write + sync ≈ total (no zero, truncation, or aggregation bug)
Buffer counts and timing scale realistically with workload
No evidence of under- or over-counted times
Checkpoint stats properly recorded in log and pg_stat_checkpointer
Math check:
0.023 s + 0.017 s = 0.040 s, total = 0.071 s => difference ≈ 0.03 s overhead => normal for control file + metadata writes.
Comparison to Prior Reports:
Test | Pre-Patch | Post-Patch | Difference |
Checkpoint duration | 6.5 s | 5.0 s | −23 |
Heavy workload test | 16 s | 8 s | −50 |
Result: It shows consistent and stable timing even under moderate pgbench load — confirming the patch is integrated and functioning correctly.
Final Status:
Category | Result |
Batched Write Stats Accuracy | Verified OK |
Timing Aggregation Correctness | Verified OK |
pg_stat_checkpointer Consistency | Verified OK |
Log Formatting | Normal |
Performance Regression | None detected |
Inference:
The reported write, sync, and total timings are consistent and realistic.
No anomalies or timing mismatches were seen.
Checkpoint performance seems stable and accurate under moderate load.
No regression or counter accumulation issues detected.
Observations:
Metric | Before Activity | After Activity | Notes |
Buffers written | 27949 | 27972 | Matches wrote 23 buffers from log |
Write time | 206882 | 206887 | Matches write=0.005 s from log |
Sync time | 840 | 877 | Matches sync=0.037 s from log |
num_done | 6 | 7 | Completed successfully |
slru_written | 8 | 9 | Matches wrote 1 SLRU buffer from log |
Stats reset | yes | yes | successful |
num_requested | 7 | 8 | manual checkpoint recorded |
Re: Checkpointer write combining
Thanks for continuing to review! I've revised the patches to
incorporate all of your feedback except for where I mention below.
There were failures in CI due to issues with max batch size, so
attached v8 also seeks to fix those.
- Melanie
On Thu, Oct 16, 2025 at 12:25 AM Chao Li wrote:
>
> 3 - 0003
> ```
> +/*
> + * Return the next buffer in the ring or InvalidBuffer if the current sweep is
> + * over.
> + */
> +Buffer
> +StrategySweepNextBuffer(BufferAccessStrategy strategy, int *sweep_cursor)
> +{
> + if (++(*sweep_cursor) >= strategy->nbuffers)
> + *sweep_cursor = 0;
> +
> + return strategy->buffers[*sweep_cursor];
> +}
> ```
>
> Feels the function comment is a bit confusing, because the function code doesn’t really perform sweep, the function is just a getter. InvalidBuffer just implies the current sweep is over.
>
> Maybe rephrase to something like: “Return the next buffer in the range. If InvalidBuffer is returned, that implies the current sweep is done."
Yes, actually I think having these helpers mention the sweep is more
confusing than anything else. I've revised them to be named more
generically and updated the comments accordingly.
> 5 - 0004
> ```
> +uint32
> +StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
> +{
> + uint32 max_possible_buffer_limit;
> + uint32 max_write_batch_size;
> + int strategy_pin_limit;
> +
> + max_write_batch_size = io_combine_limit;
> +
> + strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
> + max_possible_buffer_limit = GetPinLimit();
> +
> + max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size);
> + max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size);
> + max_write_batch_size = Max(1, max_write_batch_size);
> + max_write_batch_size = Min(max_write_batch_size, io_combine_limit);
> + Assert(max_write_batch_size < MAX_IO_COMBINE_LIMIT);
> + return max_write_batch_size;
> +}
> ```
>
> This implementation is hard to understand. I tried to simplify it:
> ```
> uint32
> StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
> {
> int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
> uint32 max_write_batch_size = Min(GetPinLimit(), (uint32)strategy_pin_limit);
>
> /* Clamp to io_combine_limit and enforce minimum of 1 */
> if (max_write_batch_size > io_combine_limit)
> max_write_batch_size = io_combine_limit;
> if (max_write_batch_size == 0)
> max_write_batch_size = 1;
>
> Assert(max_write_batch_size < MAX_IO_COMBINE_LIMIT);
> return max_write_batch_size;
> }
> ```
I agree that the implementation was hard to understand. I've not quite
gone with your version but I have rewritten it like this:
uint32
StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
{
uint32 max_write_batch_size = Min(io_combine_limit,
MAX_IO_COMBINE_LIMIT);
int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
uint32 max_possible_buffer_limit = GetPinLimit();
/* Identify the minimum of the above */
max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size);
max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size);
/* Must allow at least 1 IO for forward progress */
max_write_batch_size = Max(1, max_write_batch_size);
return max_write_batch_size;
}
Is this better?
- Melanie
Re: Checkpointer write combining
Hi all,
Considering the CI failures in earlier patch versions around “max batch size”, upon my observation I found the failures arise either from boundary conditions when io_combine_limit (GUC) is set larger than the compile-time MAX_IO_COMBINE_LIMIT or when pin limits return small/zero values due to which it produce out-of-range batch sizes or assertion failures in CI.
Comparing the approaches suggested in the thread, I think implementing (GUC + compile-time cap first, and then pin limits) could be more effective in avoiding CI failures and also we should consider the following logic conditions:
Set
io_combine_limit == 0explicitly (fallback to 1 for forward progress).Cap early to a conservative
compile_cap(MAX_IO_COMBINE_LIMIT - 1) to avoid array overflow. Otherwise ifwe confirm all slots are usable, change to MAX_IO_COMBINE_LIMIT.Apply per-strategy pin and global pin limits only if they are positive.
Use explicit typed comparisons to avoid signed/unsigned pitfalls and add a final
Assert()to capture assumptions in CI.
Implementation logic:
uint32
StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
{
uint32 max_write_batch_size;
uint32 compile_cap = MAX_IO_COMBINE_LIMIT - 1; /* conservative cap */
int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
uint32 max_possible_buffer_limit = GetPinLimit();
max_write_batch_size = (io_combine_limit == 0) ? 1 : io_combine_limit;
if (max_write_batch_size > compile_cap)
max_write_batch_size = compile_cap;
if (strategy_pin_limit > 0 &&
(uint32) strategy_pin_limit < max_write_batch_size)
max_write_batch_size = (uint32) strategy_pin_limit;
if (max_possible_buffer_limit > 0 &&
max_possible_buffer_limit < max_write_batch_size)
max_write_batch_size = max_possible_buffer_limit;
if (max_write_batch_size == 0)
max_write_batch_size = 1;
Assert(max_write_batch_size <= compile_cap);
return max_write_batch_size;
}
I hope this will be helpful for proceeding further. Looking forward to more feedback.Thanking you.Regards,Soumya
Thanks for continuing to review! I've revised the patches to
incorporate all of your feedback except for where I mention below.
There were failures in CI due to issues with max batch size, so
attached v8 also seeks to fix those.
- Melanie
On Thu, Oct 16, 2025 at 12:25 AM Chao Li <li.evan.chao@gmail.com> wrote:
>
> 3 - 0003
> ```
> +/*
> + * Return the next buffer in the ring or InvalidBuffer if the current sweep is
> + * over.
> + */
> +Buffer
> +StrategySweepNextBuffer(BufferAccessStrategy strategy, int *sweep_cursor)
> +{
> + if (++(*sweep_cursor) >= strategy->nbuffers)
> + *sweep_cursor = 0;
> +
> + return strategy->buffers[*sweep_cursor];
> +}
> ```
>
> Feels the function comment is a bit confusing, because the function code doesn’t really perform sweep, the function is just a getter. InvalidBuffer just implies the current sweep is over.
>
> Maybe rephrase to something like: “Return the next buffer in the range. If InvalidBuffer is returned, that implies the current sweep is done."
Yes, actually I think having these helpers mention the sweep is more
confusing than anything else. I've revised them to be named more
generically and updated the comments accordingly.
> 5 - 0004
> ```
> +uint32
> +StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
> +{
> + uint32 max_possible_buffer_limit;
> + uint32 max_write_batch_size;
> + int strategy_pin_limit;
> +
> + max_write_batch_size = io_combine_limit;
> +
> + strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
> + max_possible_buffer_limit = GetPinLimit();
> +
> + max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size);
> + max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size);
> + max_write_batch_size = Max(1, max_write_batch_size);
> + max_write_batch_size = Min(max_write_batch_size, io_combine_limit);
> + Assert(max_write_batch_size < MAX_IO_COMBINE_LIMIT);
> + return max_write_batch_size;
> +}
> ```
>
> This implementation is hard to understand. I tried to simplify it:
> ```
> uint32
> StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
> {
> int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
> uint32 max_write_batch_size = Min(GetPinLimit(), (uint32)strategy_pin_limit);
>
> /* Clamp to io_combine_limit and enforce minimum of 1 */
> if (max_write_batch_size > io_combine_limit)
> max_write_batch_size = io_combine_limit;
> if (max_write_batch_size == 0)
> max_write_batch_size = 1;
>
> Assert(max_write_batch_size < MAX_IO_COMBINE_LIMIT);
> return max_write_batch_size;
> }
> ```
I agree that the implementation was hard to understand. I've not quite
gone with your version but I have rewritten it like this:
uint32
StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
{
uint32 max_write_batch_size = Min(io_combine_limit,
MAX_IO_COMBINE_LIMIT);
int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
uint32 max_possible_buffer_limit = GetPinLimit();
/* Identify the minimum of the above */
max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size);
max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size);
/* Must allow at least 1 IO for forward progress */
max_write_batch_size = Max(1, max_write_batch_size);
return max_write_batch_size;
}
Is this better?
- Melanie
Re: Checkpointer write combining
> On Nov 4, 2025, at 07:34, Melanie Plageman wrote:
>
> Thanks for continuing to review! I've revised the patches to
> incorporate all of your feedback except for where I mention below.
>
> There were failures in CI due to issues with max batch size, so
> attached v8 also seeks to fix those.
>
> - Melanie
>
> On Thu, Oct 16, 2025 at 12:25 AM Chao Li wrote:
>>
>> 3 - 0003
>> ```
>> +/*
>> + * Return the next buffer in the ring or InvalidBuffer if the current sweep is
>> + * over.
>> + */
>> +Buffer
>> +StrategySweepNextBuffer(BufferAccessStrategy strategy, int *sweep_cursor)
>> +{
>> + if (++(*sweep_cursor) >= strategy->nbuffers)
>> + *sweep_cursor = 0;
>> +
>> + return strategy->buffers[*sweep_cursor];
>> +}
>> ```
>>
>> Feels the function comment is a bit confusing, because the function code doesn’t really perform sweep, the function is just a getter. InvalidBuffer just implies the current sweep is over.
>>
>> Maybe rephrase to something like: “Return the next buffer in the range. If InvalidBuffer is returned, that implies the current sweep is done."
>
> Yes, actually I think having these helpers mention the sweep is more
> confusing than anything else. I've revised them to be named more
> generically and updated the comments accordingly.
>
>> 5 - 0004
>> ```
>> +uint32
>> +StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
>> +{
>> + uint32 max_possible_buffer_limit;
>> + uint32 max_write_batch_size;
>> + int strategy_pin_limit;
>> +
>> + max_write_batch_size = io_combine_limit;
>> +
>> + strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
>> + max_possible_buffer_limit = GetPinLimit();
>> +
>> + max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size);
>> + max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size);
>> + max_write_batch_size = Max(1, max_write_batch_size);
>> + max_write_batch_size = Min(max_write_batch_size, io_combine_limit);
>> + Assert(max_write_batch_size < MAX_IO_COMBINE_LIMIT);
>> + return max_write_batch_size;
>> +}
>> ```
>>
>> This implementation is hard to understand. I tried to simplify it:
>> ```
>> uint32
>> StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
>> {
>> int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
>> uint32 max_write_batch_size = Min(GetPinLimit(), (uint32)strategy_pin_limit);
>>
>> /* Clamp to io_combine_limit and enforce minimum of 1 */
>> if (max_write_batch_size > io_combine_limit)
>> max_write_batch_size = io_combine_limit;
>> if (max_write_batch_size == 0)
>> max_write_batch_size = 1;
>>
>> Assert(max_write_batch_size < MAX_IO_COMBINE_LIMIT);
>> return max_write_batch_size;
>> }
>> ```
>
> I agree that the implementation was hard to understand. I've not quite
> gone with your version but I have rewritten it like this:
>
> uint32
> StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
> {
> uint32 max_write_batch_size = Min(io_combine_limit,
> MAX_IO_COMBINE_LIMIT);
> int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
> uint32 max_possible_buffer_limit = GetPinLimit();
>
> /* Identify the minimum of the above */
> max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size);
> max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size);
>
> /* Must allow at least 1 IO for forward progress */
> max_write_batch_size = Max(1, max_write_batch_size);
>
> return max_write_batch_size;
> }
>
> Is this better?
Yes, I think your version is safer because it enforces the max limit at runtime instead of only asserting it in debug builds.
>
> - Melanie
>
I quickly went through 0001-0006, looks good to me now. As 0007 has WIP in the subject, I skipped it.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: Checkpointer write combining
On Wed, Nov 12, 2025 at 6:40 AM BharatDB wrote:
>
> Considering the CI failures in earlier patch versions around “max batch size”, upon my observation I found the failures arise either from boundary conditions when io_combine_limit (GUC) is set larger than the compile-time MAX_IO_COMBINE_LIMIT
How could io_combine_limit be higher than MAX_IO_COMBINE_LIMIT? The
GUC is capped to MAX_IO_COMBINE_LIMIT -- see guc_parameters.dat.
> or when pin limits return small/zero values due to which it produce out-of-range batch sizes or assertion failures in CI.
This is true. But I think it can be solved with a single comparison to
1 as in the recent version.
> Comparing the approaches suggested in the thread, I think implementing (GUC + compile-time cap first, and then pin limits) could be more effective in avoiding CI failures and also we should consider the following logic conditions:
>
> Set io_combine_limit == 0 explicitly (fallback to 1 for forward progress).
The io_combine_limit GUC has a minimum value of 1 (in guc_parameters.dat)
> Use explicit typed comparisons to avoid signed/unsigned pitfalls and add a final Assert() to capture assumptions in CI.
I think my new version works.
uint32 max_write_batch_size = Min(io_combine_limit,
MAX_IO_COMBINE_LIMIT);
int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
uint32 max_possible_buffer_limit = GetPinLimit();
/* Identify the minimum of the above */
max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size);
max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size);
/* Must allow at least 1 IO for forward progress */
max_write_batch_size = Max(1, max_write_batch_size);
return max_write_batch_size;
GetAccessStrategyPinLimit() is the only function returning a signed
value here -- and it should always return a positive value (while I
wish we would use unsigned integers when a value will never be
negative, the strategy->nbuffers struct member was added a long time
ago). Then the Min() macro should work correctly and produce a value
that fits in a uint32 because of integer promotion rules.
- Melanie
Re: Checkpointer write combining
On Thu, Nov 13, 2025 at 3:30 AM Chao Li wrote:
>
> > On Nov 4, 2025, at 07:34, Melanie Plageman wrote:
> >
> >
> > uint32
> > StrategyMaxWriteBatchSize(BufferAccessStrategy strategy)
> > {
> > uint32 max_write_batch_size = Min(io_combine_limit,
> > MAX_IO_COMBINE_LIMIT);
> > int strategy_pin_limit = GetAccessStrategyPinLimit(strategy);
> > uint32 max_possible_buffer_limit = GetPinLimit();
> >
> > /* Identify the minimum of the above */
> > max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size);
> > max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size);
> >
> > /* Must allow at least 1 IO for forward progress */
> > max_write_batch_size = Max(1, max_write_batch_size);
> >
> > return max_write_batch_size;
> > }
> >
> > Is this better?
>
> Yes, I think your version is safer because it enforces the max limit at runtime instead of only asserting it in debug builds.
Cool. I've attached a v9 which is rebased over recent bufmgr.c
changes. In the process, I found a bit of cleanup to do.
> I quickly went through 0001-0006, looks good to me now. As 0007 has WIP in the subject, I skipped it.
I no longer remember why I made that patch WIP, so I've removed that
designation.
- Melanie
Re: Checkpointer write combining
> On Nov 19, 2025, at 02:49, Melanie Plageman wrote: > > I no longer remember why I made that patch WIP, so I've removed that > designation. I just reviewed 0007. It removes the second parameter "bool skip_recently_used” from SyncOneBuffer. The function is static and is only called in one place with skip_recently_used=true, thus removing the parameter seems reasonable, and without considering pinned buffer, the function is simplified a little bit. I only got a tiny comment: ``` + * We can make these check without taking the buffer content lock so ``` As you changed “this” to “these”, “check” should be changed to “checks” accordingly. Best regards, -- Chao Li (Evan) HighGo Software Co., Ltd. https://www.highgo.com/
Re: Checkpointer write combining
> On Nov 19, 2025, at 10:00, Chao Li wrote:
>
>
>
>> On Nov 19, 2025, at 02:49, Melanie Plageman wrote:
>>
>> I no longer remember why I made that patch WIP, so I've removed that
>> designation.
>
> I just reviewed 0007. It removes the second parameter "bool skip_recently_used” from SyncOneBuffer. The function is static and is only called in one place with skip_recently_used=true, thus removing the parameter seems reasonable, and without considering pinned buffer, the function is simplified a little bit.
>
> I only got a tiny comment:
> ```
> + * We can make these check without taking the buffer content lock so
> ```
>
> As you changed “this” to “these”, “check” should be changed to “checks” accordingly.
>
I just got an compile error:
```
bufmgr.c:3580:33: error: no member named 'dbId' in 'struct CkptSortItem'
3580 | batch.rlocator.dbOid = item.dbId;
| ~~~~ ^
bufmgr.c:3598:13: error: no member named 'dbId' in 'struct CkptSortItem'
3598 | if (item.dbId != batch.rlocator.dbOid)
| ~~~~ ^
2 errors generated.
make[4]: *** [bufmgr.o] Error 1
```
I tried “make clean” and “make” again, which didn’t work. I think the error is introduced by 0006.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: Checkpointer write combining
Hi Melanie, Thank you for the detailed clarifications which helped me understand the constraints much more clearly. You are absolutely right regarding the key points you specified. My initial concern came from trying to avoid cases where strategy pin limits were unexpectedly small (0 or negative) or global pin limits temporarily shrink due to memory issue / fast cycling of pins. On Wed, Nov 19, 2025 at 12:00 AM Melanie Plageman wrote: > > On Wed, Nov 12, 2025 at 6:40 AM BharatDB wrote: > > > > Considering the CI failures in earlier patch versions around “max batch size”, upon my observation I found the failures arise either from boundary conditions when io_combine_limit (GUC) is set larger than the compile-time MAX_IO_COMBINE_LIMIT > > How could io_combine_limit be higher than MAX_IO_COMBINE_LIMIT? The > GUC is capped to MAX_IO_COMBINE_LIMIT -- see guc_parameters.dat. After revisiting guc_parameters.dat, Now I see that the GUC is strictly capped at MAX_IO_COMBINE_LIMIT, so comparisons against larger values are unnecessary. Thus my earlier concern came from assuming some unbounded user-provided values are not applicable here. > > or when pin limits return small/zero values due to which it produce out-of-range batch sizes or assertion failures in CI. > > This is true. But I think it can be solved with a single comparison to > 1 as in the recent version. ok > > Comparing the approaches suggested in the thread, I think implementing (GUC + compile-time cap first, and then pin limits) could be more effective in avoiding CI failures and also we should consider the following logic conditions: > > > > Set io_combine_limit == 0 explicitly (fallback to 1 for forward progress). > > The io_combine_limit GUC has a minimum value of 1 (in guc_parameters.dat) Noted. > > Use explicit typed comparisons to avoid signed/unsigned pitfalls and add a final Assert() to capture assumptions in CI. > > I think my new version works. > > uint32 max_write_batch_size = Min(io_combine_limit, > MAX_IO_COMBINE_LIMIT); > int strategy_pin_limit = GetAccessStrategyPinLimit(strategy); > uint32 max_possible_buffer_limit = GetPinLimit(); > > /* Identify the minimum of the above */ > max_write_batch_size = Min(strategy_pin_limit, max_write_batch_size); > max_write_batch_size = Min(max_possible_buffer_limit, max_write_batch_size); > > /* Must allow at least 1 IO for forward progress */ > max_write_batch_size = Max(1, max_write_batch_size); > > return max_write_batch_size; > > GetAccessStrategyPinLimit() is the only function returning a signed > value here -- and it should always return a positive value (while I > wish we would use unsigned integers when a value will never be > negative, the strategy->nbuffers struct member was added a long time > ago). Then the Min() macro should work correctly and produce a value > that fits in a uint32 because of integer promotion rules. Th explanation about GetAccessStrategyPinLimit() (despite being int) makes sense and I agree that with the Min() macro and integer promotion rules, the outcome is always safe. Therefore, explicit typed comparisons are indeed redundant. However, after reviewing the existing code paths and your updated version, max_write_batch_size = Max(1, max_write_batch_size); => It is clear that both GetAccessStrategyPinLimit() and GetPinLimit() should always return sensible positive values and the fallback fully covers the forward-progress requirement. And I agree that it is both correct and sufficient for the CI failures we were seeing earlier. Thank you for helping me understand the reasoning behind this design. And this will be kept in mind for further work on implementing write combining. I appreciate your patience and the opportunity to refine my assumptions. Looking forward to more suggestions and feedbacks. Thanking you. Regards, Soumya
Re: Checkpointer write combining
Thanks for the review! On Tue, Nov 18, 2025 at 9:10 PM Chao Li wrote: > > > On Nov 19, 2025, at 10:00, Chao Li wrote: > > > I just reviewed 0007. It removes the second parameter "bool skip_recently_used” from SyncOneBuffer. The function is static and is only called in one place with skip_recently_used=true, thus removing the parameter seems reasonable, and without considering pinned buffer, the function is simplified a little bit. > > > > I only got a tiny comment: > > ``` > > + * We can make these check without taking the buffer content lock so > > ``` > > > > As you changed “this” to “these”, “check” should be changed to “checks” accordingly. I've made this change. Attached v10 has this. > I just got an compile error: > ``` > bufmgr.c:3580:33: error: no member named 'dbId' in 'struct CkptSortItem' > 3580 | batch.rlocator.dbOid = item.dbId; > | ~~~~ ^ > bufmgr.c:3598:13: error: no member named 'dbId' in 'struct CkptSortItem' > 3598 | if (item.dbId != batch.rlocator.dbOid) > | ~~~~ ^ > 2 errors generated. > make[4]: *** [bufmgr.o] Error 1 > ``` > > I tried “make clean” and “make” again, which didn’t work. I think the error is introduced by 0006. Are you sure you applied 0005? It is the one that adds dbId to CkptSortItem. - Melanie
Re: Checkpointer write combining
> On Nov 20, 2025, at 06:12, Melanie Plageman wrote:
>
> Are you sure you applied 0005? It is the one that adds dbId to CkptSortItem.
>
My bad. Yes, I missed to download and apply 0005.
> - Melanie
>
I went through the whole patch set again, and got a few more comments:
1 - 0002
```
+/*
+ * Prepare and write out a dirty victim buffer.
+ *
+ * Buffer must be pinned, the content lock must be held exclusively, and the
+ * buffer header spinlock must not be held. The exclusive lock is released and
+ * the buffer is returned pinned but not locked.
+ *
+ * bufdesc may be modified.
+ */
+static void
+CleanVictimBuffer(BufferDesc *bufdesc,
+ bool from_ring, IOContext io_context)
+{
+ XLogRecPtr max_lsn = InvalidXLogRecPtr;
+ LWLock *content_lock;
- /* Find smgr relation for buffer */
- if (reln == NULL)
- reln = smgropen(BufTagGetRelFileLocator(&buf->tag), INVALID_PROC_NUMBER);
+ /* Set up this victim buffer to be flushed */
+ if (!PrepareFlushBuffer(bufdesc, &max_lsn))
+ return;
```
I believe when PrepareFlushBuffer(bufdesc, &max_lsn) is false, before “return”, we should release “content_lock”.
Because the function comment clearly says “the content lock must be held exclusively”. Also, looking at the code where CleanVictimBuffer() is called:
```
if (StrategyRejectBuffer(strategy, buf_hdr, from_ring))
{
LWLockRelease(content_lock);
UnpinBuffer(buf_hdr);
continue;
}
/* Content lock is released inside CleanVictimBuffer */
CleanVictimBuffer(buf_hdr, from_ring, io_context);
```
In the previous “if” clause, it releases content_lock.
2 - 0002
```
+ * Buffer must be pinned, the content lock must be held exclusively, and the
+ * buffer header spinlock must not be held. The exclusive lock is released and
+ * the buffer is returned pinned but not locked.
+ *
+ * bufdesc may be modified.
+ */
+static void
+CleanVictimBuffer(BufferDesc *bufdesc,
+ bool from_ring, IOContext io_context)
```
The function comment says "the content lock must be held exclusively”, but from the code:
```
content_lock = BufferDescriptorGetContentLock(buf_hdr);
if (!LWLockConditionalAcquire(content_lock, LW_SHARED))
{
/*
* Someone else has locked the buffer, so give it up and loop
* back to get another one.
*/
UnpinBuffer(buf_hdr);
continue;
}
/*
* If using a nondefault strategy, and writing the buffer would
* require a WAL flush, let the strategy decide whether to go
* ahead and write/reuse the buffer or to choose another victim.
* We need the content lock to inspect the page LSN, so this can't
* be done inside StrategyGetBuffer.
*/
if (StrategyRejectBuffer(strategy, buf_hdr, from_ring))
{
LWLockRelease(content_lock);
UnpinBuffer(buf_hdr);
continue;
}
/* Content lock is released inside CleanVictimBuffer */
CleanVictimBuffer(buf_hdr, from_ring, io_context);
```
Content_lock is acquired with LW_SHARED.
3 - 0003
In CleanVictimBuffer(), more logic are added, but the content_lock leak problem is still there.
4 - 0003
```
+/*
+ * Returns true if the buffer needs WAL flushed before it can be written out.
+ * Caller must not already hold the buffer header spinlock.
+ */
+static bool
+BufferNeedsWALFlush(BufferDesc *bufdesc, XLogRecPtr *lsn)
+{
+ uint32 buf_state = LockBufHdr(bufdesc);
+
+ *lsn = BufferGetLSN(bufdesc);
+
+ UnlockBufHdr(bufdesc);
+
+ /*
+ * See buffer flushing code for more details on why we condition this on
+ * the relation being logged.
+ */
+ return buf_state & BM_PERMANENT && XLogNeedsFlush(*lsn);
+}
```
This is a new function. I am thinking that if we should only update “lsn” when not BM_PERMANENT? Because from the existing code:
```
if (buf_state & BM_PERMANENT)
XLogFlush(recptr);
```
XLogFlush should only happen when BM_PERMANENT.
5 - 0004 - I am thinking if that could be a race condition?
PageSetBatchChecksumInplace() is called once after all pages were pinned earlier, but other backends may modify the page contents while the batch is being assembled, because batching only holds content_lock per page temporarily, not across the entire run.
So that:
• Page A pinned + content lock acquired + LSN read → content lock released
• Another backend modifies Page A and sets new LSN, dirties buffer
• Page A is written by this batch using an outdated checksum / outdated page contents
6 - 0006 - Ah, 0006 seems to have solved comment 3 about BM_PERMANENT.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: Checkpointer write combining
Thanks for continuing to review this!
On Wed, Nov 19, 2025 at 9:32 PM Chao Li wrote:
>
> +static void
> +CleanVictimBuffer(BufferDesc *bufdesc,
> + bool from_ring, IOContext io_context)
> +{
> + XLogRecPtr max_lsn = InvalidXLogRecPtr;
> + LWLock *content_lock;
>
> - /* Find smgr relation for buffer */
> - if (reln == NULL)
> - reln = smgropen(BufTagGetRelFileLocator(&buf->tag), INVALID_PROC_NUMBER);
> + /* Set up this victim buffer to be flushed */
> + if (!PrepareFlushBuffer(bufdesc, &max_lsn))
> + return;
> ```
>
> I believe when PrepareFlushBuffer(bufdesc, &max_lsn) is false, before “return”, we should release “content_lock”.
Oh wow, you are so right. That's a big mistake! I would have thought a
test would fail, but it seems we don't have coverage of this. I've
fixed the code in the attached v11. I'll see how difficult it is to
write a test that covers the case where we try to do IO but someone
else has already done it.
> + * Buffer must be pinned, the content lock must be held exclusively, and the
> + * buffer header spinlock must not be held. The exclusive lock is released and
> + * the buffer is returned pinned but not locked.
>
> The function comment says "the content lock must be held exclusively”, but from the code:
> Content_lock is acquired with LW_SHARED.
Thanks, I've updated the comment.
> +static bool
> +BufferNeedsWALFlush(BufferDesc *bufdesc, XLogRecPtr *lsn)
> +{
> + uint32 buf_state = LockBufHdr(bufdesc);
> +
> + *lsn = BufferGetLSN(bufdesc);
> +
> + UnlockBufHdr(bufdesc);
> +
> + /*
> + * See buffer flushing code for more details on why we condition this on
> + * the relation being logged.
> + */
> + return buf_state & BM_PERMANENT && XLogNeedsFlush(*lsn);
> +}
>
> This is a new function. I am thinking that if we should only update “lsn” when not BM_PERMANENT?
That makes sense. I don't use the lsn unless the buffer is logged
(BM_PERMANENT), but I think it is weird for the function to set the
LSN if it is returning false. I've modified the function to set it to
InvalidXLogRecPtr when it would return false. I've also added an
assert before XLogFlush() to make sure the buffer is logged before
flushing the WAL.
> 5 - 0004 - I am thinking if that could be a race condition?
>
> PageSetBatchChecksumInplace() is called once after all pages were pinned earlier, but other backends may modify the page contents while the batch is being assembled, because batching only holds content_lock per page temporarily, not across the entire run.
> So that:
> • Page A pinned + content lock acquired + LSN read → content lock released
> • Another backend modifies Page A and sets new LSN, dirties buffer
> • Page A is written by this batch using an outdated checksum / outdated page contents
So, there is a race condition but it is slightly different from the
scenario you mention. We actually hold the content lock until after
doing the write. That means someone else can't get an exclusive lock
and modify the tuple data in the buffer. However, queries can set hint
bits while only holding a share lock. That can update the LSN (if an
FPI is required), which would cause bad things to happen when we write
out a buffer with an outdated checksum. What we do in master is make a
copy of the buffer, checksum it, and write out the copied buffer (see
PageSetChecksumCopy() and its function comment).
I have an XXX in PageSetBatchChecksumInplace() and in the commit
message for this patch explaining that it isn't committable until some
ongoing work Andres is doing adding a new lock type for setting hint
bits is committed. So, this specific part of this patch is WIP.
- Melanie
Re: Checkpointer write combining
Hi all, I applied the v11 patchset on my 19devel source code without any modifications and ran some rounds of pgbench for testing. I ran multiple workloads with different client counts and it executed successfully without any backend crashes. I am including the observations herewith for further review. 1. pgbench -c 4 -j 4 -T 10 -p 55432 postgres pgbench (19devel) starting vacuum...end. transaction type: scaling factor: 50 query mode: simple number of clients: 4 number of threads: 4 maximum number of tries: 1 duration: 10 s number of transactions actually processed: 10103 number of failed transactions: 0 (0.000%) latency average = 3.958 ms initial connection time = 4.970 ms tps = 1010.552537 (without initial connection time) 2. pgbench -c 8 -j 8 -T 120 -p 55432 postgres pgbench (19devel) starting vacuum...end. transaction type: scaling factor: 50 query mode: simple number of clients: 8 number of threads: 8 maximum number of tries: 1 duration: 120 s number of transactions actually processed: 193468 number of failed transactions: 0 (0.000%) latency average = 4.962 ms initial connection time = 8.135 ms tps = 1612.271773 (without initial connection time) 3. pgbench -c 16 -j 8 -T 180 -p 55432 postgres pgbench (19devel) starting vacuum...end. transaction type: scaling factor: 50 query mode: simple number of clients: 16 number of threads: 8 maximum number of tries: 1 duration: 180 s number of transactions actually processed: 598737 number of failed transactions: 0 (0.000%) latency average = 4.810 ms initial connection time = 13.793 ms tps = 3326.398071 (without initial connection time) I will continue testing with more workloads including forced checkpoints to see if it can trigger any edge cases or WAL flush decisions. But for now, the v11 series appears stable on my system. Looking forward to more feedback. Regards, Soumya
Re: Checkpointer write combining
Based on the ongoing discussions on Checkpointer Write Combining [1] and the last patch v11 discussed in forum, I have re-implemented the logic for CleanVictimBuffer() and BufferNeedsWALFlush() with a few changes:
static void
CleanVictimBuffer(BufferDesc *bufdesc, bool from_ring, IOContext io_context)
{
XLogRecPtr max_lsn = InvalidXLogRecPtr;
LWLock *content_lock;
content_lock = BufHdrGetContentLock(bufdesc);
LWLockAcquire(content_lock, LW_SHARED);
if (!PrepareFlushBuffer(bufdesc, &max_lsn))
{
LWLockRelease(content_lock);
return;
}
LWLockRelease(content_lock);
LWLockAcquire(content_lock, LW_EXCLUSIVE);
if (!PrepareFlushBuffer(bufdesc, &max_lsn))
{
LWLockRelease(content_lock);
return;
}
BufferSetStateWriteInProgress(bufdesc);
LWLockRelease(content_lock);
RecordBufferForBatch(bufdesc, max_lsn);
}
Here I added some extra safety checks and early-exit handling, making sure the function returns cleanly when a buffer no longer needs writing and ensuring locks are handled correctly.
static bool
BufferNeedsWALFlush(BufferDesc *bufdesc, XLogRecPtr *lsn)
{
uint32 buf_state;
buf_state = LockBufHdr(bufdesc);
if (buf_state & BM_PERMANENT)
*lsn = BufferGetLSN(bufdesc);
else
*lsn = InvalidXLogRecPtr;
UnlockBufHdr(bufdesc);
if (!(*lsn != InvalidXLogRecPtr))
return false;
return XLogNeedsFlush(*lsn);
}
I am now focusing on the PageSetBatchChecksumInplace() as mentioned in [1] and the write combining logic. I will update my implementations soon once I complete it.
I hope these corrected versions of functions will be helpful in further implementation. Looking forward to more feedback.
Regards,
Soumya
Reference:
Discussion [1] https://www.postgresql.org/message-id/CAAKRu_ZiEpE_EHww3S3-E3iznybdnX8mXSO7Wsuru7=P9Y=czQ@mail.gmail.com
Re: Checkpointer write combining
With reference to the last patches (v11) I received [1] and while reviewing Melanie’s latest feedback, I understood that PageSetBatchChecksumInplace() is currently WIP and depends on upcoming changes to hint-bit locking. It will be contrary to the flow if I propose new functional changes to checksum batching at this time. So for now I will focus on preparatory or documentation improvements until I get the updates on dependencies.
Regarding my patch attached, the patch introduces write-combining during checkpoints by batching contiguous buffers and allowing them to be written using vectorized I/O. My patch includes write-combining for checkpoint buffer flushes, contiguous buffer batching, Preserved WAL ordering, locking, and buffer state invariants. The change is currently limited to the checkpointer path (BufferSync()). So far I tested my implementation and found that all the regression (233 tests) and isolation tests (121 tests) got passed, the manual pgbench validation completed successfully and also verified pg_stat_bgwriter counters before and after checkpoints. So far the implementation is stable in my system. And currently, I am focussing on the implementation of check pointer write combining for bgwriter behavior and will update it soon after validating my implementation.
Regards,
Soumya
Reference:
[1] https://www.postgresql.org/message-id/flat/CAAKRu_ZiEpE_EHww3S3-E3iznybdnX8mXSO7Wsuru7%3DP9Y%3DczQ%40mail.gmail.com#52e4f67645f26609427d5b1fc31fdf08
Re: Checkpointer write combining
On Mon, Dec 15, 2025 at 4:36 AM Soumya S Murali wrote: > > With reference to the last patches (v11) I received [1] and while reviewing Melanie’s latest feedback, I understood that PageSetBatchChecksumInplace() is currently WIP and depends on upcoming changes to hint-bit locking. It will be contrary to the flow if I propose new functional changes to checksum batching at this time. So for now I will focus on preparatory or documentation improvements until I get the updates on dependencies. > Regarding my patch attached, the patch introduces write-combining during checkpoints by batching contiguous buffers and allowing them to be written using vectorized I/O. My patch includes write-combining for checkpoint buffer flushes, contiguous buffer batching, Preserved WAL ordering, locking, and buffer state invariants. The change is currently limited to the checkpointer path (BufferSync()). So far I tested my implementation and found that all the regression (233 tests) and isolation tests (121 tests) got passed, the manual pgbench validation completed successfully and also verified pg_stat_bgwriter counters before and after checkpoints. So far the implementation is stable in my system. Can you explain how your implementation differs from what was posted in v11 0006 [1]? That implements checkpointer write combining. I'm open to ideas for improving the code, but I don't understand how your patch is supposed to fit into the ongoing work on this thread. - Melanie [1] https://www.postgresql.org/message-id/CAAKRu_ZiEpE_EHww3S3-E3iznybdnX8mXSO7Wsuru7%3DP9Y%3DczQ%40mail.gmail.com
Re: Checkpointer write combining
On Mon, Dec 8, 2025 at 2:14 AM Soumya S Murali wrote: > > Here I made some changes in the logic of the function that only returns a real LSN when the buffer actually needs a WAL flush. If the buffer is not permanent or doesn’t need WAL, it returns false and set the LSN to InvalidXLogRecPtr, by which it can avoid confusions or unsafe downstream behaviors. Thanks for the suggestions. It would be best if you attached a patch instead of pasting it in the email like this with no formatting (and no diff). It is very hard to tell what you've changed. - Melanie
Re: Checkpointer write combining
Hi all, On Tue, Dec 16, 2025 at 3:20 AM Melanie Plageman wrote: > > On Mon, Dec 8, 2025 at 2:14 AM Soumya S Murali > wrote: > > > > Here I made some changes in the logic of the function that only returns a real LSN when the buffer actually needs a WAL flush. If the buffer is not permanent or doesn’t need WAL, it returns false and set the LSN to InvalidXLogRecPtr, by which it can avoid confusions or unsafe downstream behaviors. > > Thanks for the suggestions. It would be best if you attached a patch > instead of pasting it in the email like this with no formatting (and > no diff). It is very hard to tell what you've changed. > > - Melanie Thank you for the clarification. I understand the concern, and apologies for the earlier confusion. My intention is to stay aligned with the direction of your v11 series, so this patch contains only small, incremental changes intended to be easy to review and not conflict with ongoing work. My previous message was only meant to summarize logic I was experimenting with locally, not to propose it as a final patch. Based on the feedback, I revisited the implementation, made the necessary modifications, and verified the updated logic. I am attaching the patch for review. It has been tested with make check and make -C src/test/isolation check. Thank you again for the guidance. I hope this is helpful for the ongoing work, and I am looking forward to further feedback. Regards Soumya
Re: Checkpointer write combining
Hi all, On Tue, Dec 16, 2025 at 3:18 AM Melanie Plageman wrote: > > On Mon, Dec 15, 2025 at 4:36 AM Soumya S Murali > wrote: > > > > With reference to the last patches (v11) I received [1] and while reviewing Melanie’s latest feedback, I understood that PageSetBatchChecksumInplace() is currently WIP and depends on upcoming changes to hint-bit locking. It will be contrary to the flow if I propose new functional changes to checksum batching at this time. So for now I will focus on preparatory or documentation improvements until I get the updates on dependencies. > > Regarding my patch attached, the patch introduces write-combining during checkpoints by batching contiguous buffers and allowing them to be written using vectorized I/O. My patch includes write-combining for checkpoint buffer flushes, contiguous buffer batching, Preserved WAL ordering, locking, and buffer state invariants. The change is currently limited to the checkpointer path (BufferSync()). So far I tested my implementation and found that all the regression (233 tests) and isolation tests (121 tests) got passed, the manual pgbench validation completed successfully and also verified pg_stat_bgwriter counters before and after checkpoints. So far the implementation is stable in my system. > > Can you explain how your implementation differs from what was posted > in v11 0006 [1]? That implements checkpointer write combining. I'm > open to ideas for improving the code, but I don't understand how your > patch is supposed to fit into the ongoing work on this thread. > > - Melanie > > [1] https://www.postgresql.org/message-id/CAAKRu_ZiEpE_EHww3S3-E3iznybdnX8mXSO7Wsuru7%3DP9Y%3DczQ%40mail.gmail.com Thank you for the question. My patch is not intended to replace or redesign v11-0006. I am fully aligned with that patch and treated it as the baseline for my work. The work I sent is intentionally incremental, rather than introducing a new batching logic. v11-0006 already implements the core checkpointer write-combining logic (batch formation, contiguity checks, WAL ordering, pin limits, and IO issuance). I did not change that structure. My changes focus on correctness around existing CleanVictimBuffer() ensuring content locks are always released on early exit paths and making the shared exclusive lock transitions explicit. This directly addresses the lock-handling issue you pointed out earlier in the thread. And the BufferNeedsWALFlush() clarifying semantics so that an LSN is only returned when the buffer is logged (BM_PERMANENT), otherwise explicitly setting it to InvalidXLogRecPtr. This matches the direction you mentioned about avoiding confusing or unsafe LSN propagation. I intentionally did not modify PageSetBatchChecksumInplace(), since it is clearly marked WIP and depended on the hint-bit locking work as you mentioned. I just validated the v11-0006 design on a fresh tree, done a few small correctness cleanups that do not alter behavior and done the testing like make check, isolation tests and manual checkpoint validation for confirmation. I hope you find this useful. Thank you for the guidance and patience. Looking forward to more feedback. Regards, Soumya
Re: Checkpointer write combining
On Tue, Dec 16, 2025 at 11:46 PM Soumya S Murali
wrote:
>
> Thank you for the clarification.
> I understand the concern, and apologies for the earlier confusion. My
> intention is to stay aligned with the direction of your v11 series, so
> this patch contains only small, incremental changes intended to be
> easy to review and not conflict with ongoing work.
> My previous message was only meant to summarize logic I was
> experimenting with locally, not to propose it as a final patch. Based
> on the feedback, I revisited the implementation, made the necessary
> modifications, and verified the updated logic.
> I am attaching the patch for review. It has been tested with make
> check and make -C src/test/isolation check.
> Thank you again for the guidance. I hope this is helpful for the
> ongoing work, and I am looking forward to further feedback.
I took a look at your patch and the first two parts were already fixed
in a previous version
--- a/src/backend/storage/buffer/bufmgr.c
+++ b/src/backend/storage/buffer/bufmgr.c
@@ -4405,7 +4405,7 @@ BufferNeedsWALFlush(BufferDesc *bufdesc, XLogRecPtr *lsn)
UnlockBufHdr(bufdesc);
/* Skip all WAL flush logic if relation is not logged */
- if (!(*lsn != InvalidXLogRecPtr))
+ if (!XLogRecPtrIsValid(*lsn))
return false;
@@ -4433,6 +4433,12 @@ CleanVictimBuffer(BufferDesc *bufdesc, bool
from_ring, IOContext io_context)
content_lock = BufHdrGetContentLock(bufdesc);
LWLockAcquire(content_lock, LW_SHARED);
+ if (!PrepareFlushBuffer(bufdesc, &max_lsn))
+ {
+ LWLockRelease(content_lock);
+ return;
+ }
+
And I don't understand the last parts of the diff.
@@ -4440,19 +4446,14 @@ CleanVictimBuffer(BufferDesc *bufdesc, bool
from_ring, IOContext io_context)
LWLockRelease(content_lock);
LWLockAcquire(content_lock, LW_EXCLUSIVE);
- /*
- * Mark the buffer ready for checksum and write.
- */
- PrepareBufferForCheckpoint(bufdesc, &max_lsn);
+ if (!PrepareFlushBuffer(bufdesc, &max_lsn))
+ {
+ LWLockRelease(content_lock);
+ return;
+ }
/* Release exclusive lock; the batch will write the page later */
LWLockRelease(content_lock);
-
- /*
- * Add LSN to caller's batch tracking.
- * Caller handles XLogFlush() using highest LSN.
- */
- PrepareBufferForCheckpoint(bufdesc, max_lsn);
}
AFAIK, there has never been a function called
PrepareBufferForCheckpoint() and my current patchset doesn't have it
either.
- Melanie
Re: Checkpointer write combining
Hi all,
On Wed, Dec 17, 2025 at 9:09 PM Melanie Plageman
wrote:
>
> On Tue, Dec 16, 2025 at 11:46 PM Soumya S Murali
> wrote:
> >
> > Thank you for the clarification.
> > I understand the concern, and apologies for the earlier confusion. My
> > intention is to stay aligned with the direction of your v11 series, so
> > this patch contains only small, incremental changes intended to be
> > easy to review and not conflict with ongoing work.
> > My previous message was only meant to summarize logic I was
> > experimenting with locally, not to propose it as a final patch. Based
> > on the feedback, I revisited the implementation, made the necessary
> > modifications, and verified the updated logic.
> > I am attaching the patch for review. It has been tested with make
> > check and make -C src/test/isolation check.
> > Thank you again for the guidance. I hope this is helpful for the
> > ongoing work, and I am looking forward to further feedback.
>
> I took a look at your patch and the first two parts were already fixed
> in a previous version
>
> --- a/src/backend/storage/buffer/bufmgr.c
> +++ b/src/backend/storage/buffer/bufmgr.c
> @@ -4405,7 +4405,7 @@ BufferNeedsWALFlush(BufferDesc *bufdesc, XLogRecPtr *lsn)
> UnlockBufHdr(bufdesc);
>
> /* Skip all WAL flush logic if relation is not logged */
> - if (!(*lsn != InvalidXLogRecPtr))
> + if (!XLogRecPtrIsValid(*lsn))
> return false;
>
>
> @@ -4433,6 +4433,12 @@ CleanVictimBuffer(BufferDesc *bufdesc, bool
> from_ring, IOContext io_context)
> content_lock = BufHdrGetContentLock(bufdesc);
> LWLockAcquire(content_lock, LW_SHARED);
>
> + if (!PrepareFlushBuffer(bufdesc, &max_lsn))
> + {
> + LWLockRelease(content_lock);
> + return;
> + }
> +
>
> And I don't understand the last parts of the diff.
>
> @@ -4440,19 +4446,14 @@ CleanVictimBuffer(BufferDesc *bufdesc, bool
> from_ring, IOContext io_context)
> LWLockRelease(content_lock);
> LWLockAcquire(content_lock, LW_EXCLUSIVE);
>
> - /*
> - * Mark the buffer ready for checksum and write.
> - */
> - PrepareBufferForCheckpoint(bufdesc, &max_lsn);
> + if (!PrepareFlushBuffer(bufdesc, &max_lsn))
> + {
> + LWLockRelease(content_lock);
> + return;
> + }
>
> /* Release exclusive lock; the batch will write the page later */
> LWLockRelease(content_lock);
> -
> - /*
> - * Add LSN to caller's batch tracking.
> - * Caller handles XLogFlush() using highest LSN.
> - */
> - PrepareBufferForCheckpoint(bufdesc, max_lsn);
> }
>
> AFAIK, there has never been a function called
> PrepareBufferForCheckpoint() and my current patchset doesn't have it
> either.
>
> - Melanie
Thank you for reviewing the patch and for the clarification.
It seems I was working on the v11 patch version that I had received
from November, and I did not have the newer fixes that already
addressed the XLogRecPtrIsValid() check and the shared-lock early
return case in CleanVictimBuffer(). That's why the first part of my
changes duplicated the work that has already been fixed.
Regarding the latter part of the diff, the reason I attempted that
change was that in my local tree the code was still performing both
WAL–LSN read + dirty check inside the exclusive lock followed by
marking/queuing the buffer for write. And I initially interpreted that
section as functionally similar to the description of
PrepareBufferForCheckpoint() from the early discussion in the thread.
Because I didn't have the newer version of the patchset where this
function was removed or renamed, I refactored it into a second
PrepareFlushBuffer() call to ensure correctness on re-checking after
lock upgrade and to keep failure paths symmetrical (especially unlock
and early return). I now understand that this was based on an outdated
context and why it conflicts with the current patch flow. So I will
rebase my work on the latest version of the patch and will drop that
section to avoid misalignment.
If there are any specific areas where I can help align with the
ongoing work, please let me know I’m happy to continue contributing in
the direction you are taking the patchset.
Regards,
Soumya
Re: Checkpointer write combining
Attached v12 fixes a variety of buglets I found throughout the patch set. I've also done quite a bit of refactoring. The scope of the refactoring varies from inlining some helpers to introducing new input argument structs. 0001 is independently valuable as it optimizes StrategyRejectBuffer() a bit and makes GetVictimBuffer() cleaner 0002-0007 were largely present in older versions of the patch set 0008 is new -- it is an early version of batching for normal backends flushing a buffer to obtain a clean one. Right now, it checks if the two blocks succeeding the target block are in shared buffers and dirty, and, if so, writes them out with the target buffer. I haven't started testing or benchmarking it because I need to convert bgwriter to use write combining to be able to benchmark it effectively. But I thought I would get the code out there sooner rather than later. It's a lot harder with my current code structure to add the target block's predecessor if it is dirty and read to write out. I wonder how important this is vs just the two succeeding blocks. - Melanie
Re: Checkpointer write combining
> On Jan 14, 2026, at 06:24, Melanie Plageman wrote:
>
> Attached v12 fixes a variety of buglets I found throughout the patch set.
>
> I've also done quite a bit of refactoring. The scope of the
> refactoring varies from inlining some helpers to introducing new input
> argument structs.
>
> 0001 is independently valuable as it optimizes StrategyRejectBuffer()
> a bit and makes GetVictimBuffer() cleaner
>
> 0002-0007 were largely present in older versions of the patch set
>
> 0008 is new -- it is an early version of batching for normal backends
> flushing a buffer to obtain a clean one. Right now, it checks if the
> two blocks succeeding the target block are in shared buffers and
> dirty, and, if so, writes them out with the target buffer. I haven't
> started testing or benchmarking it because I need to convert bgwriter
> to use write combining to be able to benchmark it effectively. But I
> thought I would get the code out there sooner rather than later.
>
> It's a lot harder with my current code structure to add the target
> block's predecessor if it is dirty and read to write out. I wonder how
> important this is vs just the two succeeding blocks.
>
> - Melanie
>
Hi Melanie,
I went through the patch set again today, and paid special attention to 0001 and 0008 that I seemed to not review before. Here are comments I got today:
1 - 0001
```
--- a/src/include/storage/buf_internals.h
+++ b/src/include/storage/buf_internals.h
@@ -15,6 +15,7 @@
#ifndef BUFMGR_INTERNALS_H
#define BUFMGR_INTERNALS_H
+#include "access/xlogdefs.h"
```
I tried to build without adding this include, build still passed. I think that’s because there is a include path: storage/bufmgr.h -> storage/bufpage.h -> access/xlogger.h.
So, maybe we can remove this include.
2 - 0001
```
+ * The buffer must be pinned and content locked and the buffer header spinlock
+ * must not be held.
+ *
* Returns true if buffer manager should ask for a new victim, and false
* if this buffer should be written and re-used.
*/
bool
StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf, bool from_ring)
{
+ XLogRecPtr lsn;
+
+ if (!strategy)
+ return false;
```
As the new comment stated, the buffer must be pinned, maybe we can add an assert to ensure that:
```
Assert(BufferIsPinned(buffer));
```
Similarly, maybe we can also assert the locks are not held:
```
Assert(BufferDescriptorGetContentLock(buffer));
Assert(!pg_atomic_read_u32(&buf->state) & BM_LOCKED);
```
3 - 0001 - bufmgr.c - BufferNeedsWALFlush()
```
+ buffer = BufferDescriptorGetBuffer(bufdesc);
+ page = BufferGetPage(buffer);
+
+ Assert(BufferIsValid(buffer));
```
I think the Assert should be moved to before "page = BufferGetPage(buffer);”.
4 - 0001 - bufmgr.c
```
+/*
+ * Returns true if the buffer needs WAL flushed before it can be written out.
+ * *lsn is set to the current page LSN.
+ *
+ * If the result is required to be correct, the caller must hold a buffer
+ * content lock. If they only hold a shared content lock, we'll need to
+ * acquire the buffer header spinlock, so they must not already hold it.
+ *
+ * If the buffer is unlogged, *lsn shouldn't be used by the caller and is set
+ * to InvalidXLogRecPtr.
+ */
+bool
+BufferNeedsWALFlush(BufferDesc *bufdesc, bool exclusive, XLogRecPtr *lsn)
```
I think the “exclusive" parameter is a bit subtle. The parameter is not explicitly explained in the header comment, though there is a paragraph that explains different behaviors when the caller hold and not hold content lock. Maybe we can rename to a more direct name: hold_exclusive_content_lock, or a shorter one hold_content_lock.
5 - 0002 - commit message
```
actual buffer flushing step. This separation procides symmetry with
```
Typo: procides -> provides
6 - 0002
```
+ * We must hold the buffer header lock when examining the page LSN since
+ * don't have buffer exclusively locked in all cases.
```
Looks like it’s better to add “we” between “since” and “don’t” => since we don’t have ...
7 - 0002
```
+/*
+ * Prepare the buffer with bufdesc for writing. Returns true if the buffer
+ * actually needs writing and false otherwise. lsn returns the buffer's LSN if
+ * the table is logged.
+ */
+static bool
+PrepareFlushBuffer(BufferDesc *bufdesc, XLogRecPtr *lsn)
+{
uint32 buf_state;
/*
@@ -4425,42 +4445,16 @@ FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object,
* someone else flushed the buffer before we could, so we need not do
* anything.
*/
- if (!StartBufferIO(buf, false, false))
- return;
-
- /* Setup error traceback support for ereport() */
- errcallback.callback = shared_buffer_write_error_callback;
- errcallback.arg = buf;
- errcallback.previous = error_context_stack;
- error_context_stack = &errcallback;
-
- /* Find smgr relation for buffer */
- if (reln == NULL)
- reln = smgropen(BufTagGetRelFileLocator(&buf->tag), INVALID_PROC_NUMBER);
-
- TRACE_POSTGRESQL_BUFFER_FLUSH_START(BufTagGetForkNum(&buf->tag),
- buf->tag.blockNum,
- reln->smgr_rlocator.locator.spcOid,
- reln->smgr_rlocator.locator.dbOid,
- reln->smgr_rlocator.locator.relNumber);
-
- buf_state = LockBufHdr(buf);
-
- /*
- * Run PageGetLSN while holding header lock, since we don't have the
- * buffer locked exclusively in all cases.
- */
- recptr = BufferGetLSN(buf);
+ if (!StartBufferIO(bufdesc, false, false))
+ return false;
- /* To check if block content changes while flushing. - vadim 01/17/97 */
- UnlockBufHdrExt(buf, buf_state,
- 0, BM_JUST_DIRTIED,
- 0);
+ *lsn = InvalidXLogRecPtr;
+ buf_state = LockBufHdr(bufdesc);
```
The header comment says “lsn returns the buffer's LSN if the table is logged”, which looks inaccurate, because if StartBufferIO() is true, the function returns early without setting *lsn.
8 - 0008 - comment message
```
When flushing a dirty buffer, check if it the two blocks following it
```
Nit: “if it the” -> “if the"
9 - 0008
```
+ * Check if the blocks after my block are in shared buffers and dirty and if
+ * it is, write them out too
```
Nit: “if it is” -> “if they are”
10 - 0008
```
+ BlockNumber max_batch_size = 3; /* we only look for two successors */
```
Using type BlockNumber for batch size seems odd. I would suggest change to uint32.
11 - 0008 - WriteBatchInit()
```
+ LockBufHdr(batch_start);
+ batch->max_lsn = BufferGetLSN(batch_start);
+ UnlockBufHdr(batch_start);
```
Should we check unlogged buffer before assigning max_lsn? In previous commits, we have done that in many places.
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: Checkpointer write combining
On Wed, Jan 14, 2026 at 2:49 AM Chao Li wrote:
>
>
> I went through the patch set again today, and paid special attention to 0001 and 0008 that I seemed to not review before. Here are comments I got today:
Thanks! v13 attached.
> --- a/src/include/storage/buf_internals.h
> +++ b/src/include/storage/buf_internals.h
> @@ -15,6 +15,7 @@
> #ifndef BUFMGR_INTERNALS_H
> #define BUFMGR_INTERNALS_H
>
> +#include "access/xlogdefs.h"
>
> I tried to build without adding this include, build still passed. I think that’s because there is a include path: storage/bufmgr.h -> storage/bufpage.h -> access/xlogger.h.
>
> So, maybe we can remove this include.
Generally, at least for new code, we try to avoid transitive includes.
> + * The buffer must be pinned and content locked and the buffer header spinlock
> + * must not be held.
> + *
> * Returns true if buffer manager should ask for a new victim, and false
> * if this buffer should be written and re-used.
> */
> bool
> StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf, bool from_ring)
> {
> + XLogRecPtr lsn;
> +
> + if (!strategy)
> + return false;
> ```
>
> As the new comment stated, the buffer must be pinned, maybe we can add an assert to ensure that:
> ```
> Assert(BufferIsPinned(buffer));
> ```
>
> Similarly, maybe we can also assert the locks are not held:
> ```
> Assert(BufferDescriptorGetContentLock(buffer));
> Assert(!pg_atomic_read_u32(&buf->state) & BM_LOCKED);
I've added something like this.
>
> 3 - 0001 - bufmgr.c - BufferNeedsWALFlush()
> ```
> + buffer = BufferDescriptorGetBuffer(bufdesc);
> + page = BufferGetPage(buffer);
> +
> + Assert(BufferIsValid(buffer));
> ```
>
> I think the Assert should be moved to before "page = BufferGetPage(buffer);”.
I just deleted the assert -- BufferGetPage() already does it.
> +bool
> +BufferNeedsWALFlush(BufferDesc *bufdesc, bool exclusive, XLogRecPtr *lsn)
> ```
>
> I think the “exclusive" parameter is a bit subtle. The parameter is not explicitly explained in the header comment, though there is a paragraph that explains different behaviors when the caller hold and not hold content lock. Maybe we can rename to a more direct name: hold_exclusive_content_lock, or a shorter one hold_content_lock.
I've done this.
I've also gone and fixed the various typos in code and commit messages
you mentioned.
> +/*
> + * Prepare the buffer with bufdesc for writing. Returns true if the buffer
> + * actually needs writing and false otherwise. lsn returns the buffer's LSN if
> + * the table is logged.
> + */
> +static bool
> +PrepareFlushBuffer(BufferDesc *bufdesc, XLogRecPtr *lsn)
> +{
> uint32 buf_state;
>
> /*
> @@ -4425,42 +4445,16 @@ FlushBuffer(BufferDesc *buf, SMgrRelation reln, IOObject io_object,
> * someone else flushed the buffer before we could, so we need not do
> * anything.
> */
> - if (!StartBufferIO(buf, false, false))
> - return;
>
> The header comment says “lsn returns the buffer's LSN if the table is logged”, which looks inaccurate, because if StartBufferIO() is true, the function returns early without setting *lsn.
Yes, good point. I should initialize it to InvalidXLogRecPtr before
calling StartBufferIO() and document it appropriately. I've done that.
While looking at this, I realized that PrepareFlushBuffer() becomes
useless once I make normal (non-strategy) buffer flushes do write
combining. This inspired a refactor whichI think simplifies the code.
Unfortunately, it means this patch set introduces PrepareFlushBuffer()
in 0001 and then deletes it in 0008. I'm not really sure what to do
about that, but maybe it will come to me later.
> + BlockNumber max_batch_size = 3; /* we only look for two successors */
> ```
>
> Using type BlockNumber for batch size seems odd. I would suggest change to uint32.
Right, at the least, I wasn't consistent with which one to use. I've changed it.
> 11 - 0008 - WriteBatchInit()
> ```
> + LockBufHdr(batch_start);
> + batch->max_lsn = BufferGetLSN(batch_start);
> + UnlockBufHdr(batch_start);
> ```
>
> Should we check unlogged buffer before assigning max_lsn? In previous commits, we have done that in many places.
Good point, when fixing this, I realized that I was getting the page
LSN more times than I needed to for the victim buffer. I restructured
it in a way that I think is more clear.
On a separate note, I've made some other changes -- like getting rid
of the BufferBlockRequirements struct I added, because I realized that
was just a BufferTag.
And I found a few places where I hadn't documented my expectations
around the buffer header spinlock. Because I'm checking fields in the
buffer header for a heuristic, I'm bending the rules about concurrency
control. Each time I look at the patch, I find a new mistake in how
I'm handling access to the buffer header.
Speaking of which, periodically I see a test failure related to a
block having invalid contents (in 027_stream_regress). It's not
reproducible, so I haven't investigated much yet. There's at least one
bug in this patch set that needs shaking out, but I think that will
have to wait for another day. I'll probably want to add some tests.
- Melanie
Re: Checkpointer write combining
Hi all, Thank you all for the patches. I am keeping this as a single patch because the refactoring, batching behavior and instrumentation are tightly coupled and all serve one purpose to reduce checkpoint writeback overhead while making the effect observable. Due to version and context differences, the patches did not apply cleanly in my development environment. Instead, I studied the patches and went through the logic in detail and then implemented the same ideas directly in my current tree adapting them wherever needed. The implementation was then validated with instrumentation and measurements. Before batching: 2026-01-22 17:27:26.969 IST [148738] LOG: checkpoint complete: wrote 15419 buffers (94.1%), wrote 1 SLRU buffers; 0 WAL file(s) added, 0 removed, 25 recycled; write=0.325 s, sync=0.284 s, total=0.754 s; sync files=30, longest=0.227 s, average=0.010 s; distance=407573 kB, estimate=407573 kB; lsn=0/1A5B8E30, redo lsn=0/1A5B8DD8 After batching: 2026-01-22 17:31:36.165 IST [148738] LOG: checkpoint complete: wrote 13537 buffers (82.6%), wrote 1 SLRU buffers; 0 WAL file(s) added, 0 removed, 25 recycled; write=0.260 s, sync=0.211 s, total=0.625 s; sync files=3, longest=0.205 s, average=0.070 s; distance=404310 kB, estimate=407247 kB; lsn=0/3308E738, redo lsn=0/3308E6E0 Debug instrumentation with (batch size = 16) confirms the batching behavior itself, buffers_written = 6196 writeback_calls = 389 On average: I am getting 15.9 i.e approx 16 buffers per writeback This shows that writebacks are issued per batch rather than per buffer, while WAL ordering and durability semantics remain unchanged. The change remains localized to BufferSync() and is intended to be a conservative and measurable improvement to checkpoint I/O behavior. I am attaching the patches herewith for review. I am happy to adjust the approach if there are concerns or suggestions. Looking forward to more feedback. Regards, Soumya
Re: Checkpointer write combining
Hi all, > Thank you all for the patches. > I am keeping this as a single patch because the refactoring, batching > behavior and instrumentation are tightly coupled and all serve one > purpose to reduce checkpoint writeback overhead while making the > effect observable. Due to version and context differences, the patches > did not apply cleanly in my development environment. Instead, I > studied the patches and went through the logic in detail and then > implemented the same ideas directly in my current tree adapting them > wherever needed. The implementation was then validated with > instrumentation and measurements. > > Before batching: > 2026-01-22 17:27:26.969 IST [148738] LOG: checkpoint complete: wrote > 15419 buffers (94.1%), wrote 1 SLRU buffers; 0 WAL file(s) added, 0 > removed, 25 recycled; write=0.325 s, sync=0.284 s, total=0.754 s; sync > files=30, longest=0.227 s, average=0.010 s; distance=407573 kB, > estimate=407573 kB; lsn=0/1A5B8E30, redo lsn=0/1A5B8DD8 > > After batching: > 2026-01-22 17:31:36.165 IST [148738] LOG: checkpoint complete: wrote > 13537 buffers (82.6%), wrote 1 SLRU buffers; 0 WAL file(s) added, 0 > removed, 25 recycled; write=0.260 s, sync=0.211 s, total=0.625 s; sync > files=3, longest=0.205 s, average=0.070 s; distance=404310 kB, > estimate=407247 kB; lsn=0/3308E738, redo lsn=0/3308E6E0 > > Debug instrumentation with (batch size = 16) confirms the batching > behavior itself, > buffers_written = 6196 > writeback_calls = 389 > On average: I am getting 15.9 i.e approx 16 buffers per writeback > This shows that writebacks are issued per batch rather than per > buffer, while WAL ordering and durability semantics remain unchanged. > The change remains localized to BufferSync() and is intended to be a > conservative and measurable improvement to checkpoint I/O behavior. I > am attaching the patches herewith for review. > I am happy to adjust the approach if there are concerns or > suggestions. Looking forward to more feedback. > With reference to my previous patch related to the batching behavior, I evaluated batch sizes 8, 16, and 32 under identical workloads. I am attaching the log for 8, 16 and 32. All conclusions are based on actual checkpoint logs and DEBUG BufferSync statistics: Batch size = 8 LOG: checkpoint complete: wrote 12622 buffers (77.0%); write=0.113 s, sync=0.195 s, total=0.485 s; sync files=37 DEBUG: checkpoint BufferSync stats: buffers_written=9923, writeback_calls=1242 Avg: 7.989 approx 8 buffers per writeback. Batch size = 16 LOG: checkpoint complete: wrote 13537 buffers (82.6%); write=0.260 s, sync=0.211 s, total=0.625 s; sync files=3 DEBUG: checkpoint BufferSync stats: buffers_written=6196, writeback_calls=389 Avg: 15.9 approx 16 buffers per writeback. Batch size = 32 LOG: checkpoint complete: wrote 12914 buffers (78.8%); write=0.116 s, sync=0.136 s, total=0.442 s; sync files=5 DEBUG: checkpoint BufferSync stats: buffers_written=12914, writeback_calls=1616 Avg: 7.99 approx 8 buffers per writeback. Batch 16 significantly reduces sync fan-out (as low as 3 files per checkpoint), but this comes at the cost of longer individual sync operations, resulting in higher total checkpoint time (≈0.625 s). Batch 32 provides a better balance, maintaining low sync fragmentation while avoiding long sync stalls, yielding the lowest overall checkpoint time (≈0.442 s). I am attaching the patch with batch size fixed as 32 for now for further review. Please let me know if further workloads or instrumentation would be useful. Regards Soumya
Re: Checkpointer write combining
On Wed, Jan 14, 2026 at 6:35 PM Melanie Plageman wrote: > > Thanks! v13 attached. I've added background writer write combining and then spent some time refactoring and benchmarking this over the last few weeks, and I've realized I won't be able to get it in shape for Postgres 19. I've attached version 14 here with my WIP code so I can come back to it in the next release. 0012 is an invasive refactor of GetVictimBuffer() and all the functions it calls that needs to be split apart into smaller commits and redistributed throughout the other patches in the set. Other than that, there are a number of todos both in the code and from a benchmarking perspective: - Probe for preceding as well as following blocks when looking for blocks to combine - Experiment with different batch sizes - Enable and test bulkread and vacuum write combining I also periodically get this troubling warning: "WARNING: invalid page in block 2 of relation "base/16384/2608_fsm"; zeroing out page". So clearly there's at least one bug somewhere. FWIW benchmarks showed a large improvement from backend and bgwriter write combining, but I'll provide more detailed output from benchmarks when I post a more reviewable patch set. 0001 and 0002 are completely independent cleanup that should be pushed anyway, so I might do that, but I didn't want to do so without having posted on the list at least once. - Melanie
Re: Checkpointer write combining
> On Feb 20, 2026, at 07:41, Melanie Plageman wrote:
>
> On Wed, Jan 14, 2026 at 6:35 PM Melanie Plageman
> wrote:
>>
>> Thanks! v13 attached.
>
> I've added background writer write combining and then spent some time
> refactoring and benchmarking this over the last few weeks, and I've
> realized I won't be able to get it in shape for Postgres 19. I've
> attached version 14 here with my WIP code so I can come back to it in
> the next release.
>
> 0012 is an invasive refactor of GetVictimBuffer() and all the
> functions it calls that needs to be split apart into smaller commits
> and redistributed throughout the other patches in the set. Other than
> that, there are a number of todos both in the code and from a
> benchmarking perspective:
>
> - Probe for preceding as well as following blocks when looking for
> blocks to combine
> - Experiment with different batch sizes
> - Enable and test bulkread and vacuum write combining
>
> I also periodically get this troubling warning: "WARNING: invalid
> page in block 2 of relation "base/16384/2608_fsm"; zeroing out page".
> So clearly there's at least one bug somewhere.
>
> FWIW benchmarks showed a large improvement from backend and bgwriter
> write combining, but I'll provide more detailed output from benchmarks
> when I post a more reviewable patch set.
>
> 0001 and 0002 are completely independent cleanup that should be pushed
> anyway, so I might do that, but I didn't want to do so without having
> posted on the list at least once.
>
> - Melanie
>
A few comments for v14:
1 - 0001
```
- FlushBuffer(buf, reln, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
+ FlushBuffer(buf, reln, io_object, io_context);
```
This changes the hardcode IOOBJECT_RELATION to io_object when calling FlushBuffer(). But FlushBuffer() itself still uses IOOBJECT_RELATION instead of io_object, so the change will actually not take effective:
```
pgstat_count_io_op_time(IOOBJECT_RELATION, io_context,
IOOP_WRITE, io_start, 1, BLCKSZ);
```
So, an update in FlushBuffer() is also needed.
2 - 0003 - freelist.c
```
bool
StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf, bool from_ring)
{
+ Assert(strategy);
+
/* We only do this in bulkread mode */
if (strategy->btype != BAS_BULKREAD)
return false;
@@ -795,8 +800,14 @@ StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf, bool from_r
strategy->buffers[strategy->current] != BufferDescriptorGetBuffer(buf))
return false;
+ Assert(BufferIsLockedByMe(BufferDescriptorGetBuffer(buf)));
+ Assert(!(pg_atomic_read_u64(&buf->state) & BM_LOCKED));
```
I don’t quite understand Assert(!(pg_atomic_read_u64(&buf->state) & BM_LOCKED));
The comment says “the buffer header spinlock must not be held,” but I doubt this Assert actually ensures that. Since BM_LOCKED is just a bit in a shared state, isn't it possible for a concurrent backend to grab the lock right when we’re checking it?
If a concurrent process locks the header a split-second before the Assert, we’ll get a false-positive crash in a dev environment even though the code is fine. If they lock it a split-second after, then the Assert didn't really catch anything. It feels like a race condition either way.
I think the only way to truly ensure a spinlock is "not held" is to actually acquire it. If we’re just checking the bit like this, it’s just a snapshot that might be stale by the time the instruction finishes. What was the specific worry here—a self-deadlock, or something else?
3 - 0004
```
+typedef enum BufferUsageCountChange
+{
+ BUC_ZERO,
+ BUC_MAX_ONE,
+ BUC_ONE,
+} BufferUsageCountChange;
```
Can we add some brief comments to explain every enum item? I feel hard to guess the meaning from the names without further reading the code.
4 - 0005 - bufmgr.c
```
+/*
+ * Prepare bufdesc for eager flushing.
+ *
+ * Given bufnum, return the buffer descriptor of the buffer to eagerly flush,
+ * pinned and locked and with BM_IO_IN_PROGRESS set, or NULL if this buffer
+ * does not contain a block that should be flushed.
+ *
+ * If returning a buffer, also return its LSN.
+ */
+static BufferDesc *
+PrepareOrRejectEagerFlushBuffer(Buffer bufnum)
```
This header comment looks stale.
* It says “and with BM_IO_IN_PROGRESS set”, but I don’t see where BM_IO_IN_PROGRESS is set in this function.
* It says “also return its LSN”, but I don’t see LSN is returned.
5 - 0006
```
+ /* Start IO on the first buffer */
+ if (!StartBufferIO(buf_hdr, false, false))
+ goto clean;
```
This failure branch feels like leaking the content lock. The buffer was already share-locked via BufferLockConditional() earlier, and I don’t see the “clean" path unlock that content lock before returning.
6 - 0009
```
+ FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
+ UnpinBuffer(bufHdr);
+
+ ScheduleBufferTagForWriteback(wb_context, IOCONTEXT_NORMAL, &bufHdr->tag);
```
bufHdr is unlocked and unpinned, it might be unsafe to still use bufHdr->tag. I think we can copy bufHdr->tag to a local variable before unlock the buffer.
~~ My brain is stuck, I will continue 0010 tomorrow ~~
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: Checkpointer write combining
> On Feb 25, 2026, at 14:52, Chao Li wrote:
>
>
>
>> On Feb 20, 2026, at 07:41, Melanie Plageman wrote:
>>
>> On Wed, Jan 14, 2026 at 6:35 PM Melanie Plageman
>> wrote:
>>>
>>> Thanks! v13 attached.
>>
>> I've added background writer write combining and then spent some time
>> refactoring and benchmarking this over the last few weeks, and I've
>> realized I won't be able to get it in shape for Postgres 19. I've
>> attached version 14 here with my WIP code so I can come back to it in
>> the next release.
>>
>> 0012 is an invasive refactor of GetVictimBuffer() and all the
>> functions it calls that needs to be split apart into smaller commits
>> and redistributed throughout the other patches in the set. Other than
>> that, there are a number of todos both in the code and from a
>> benchmarking perspective:
>>
>> - Probe for preceding as well as following blocks when looking for
>> blocks to combine
>> - Experiment with different batch sizes
>> - Enable and test bulkread and vacuum write combining
>>
>> I also periodically get this troubling warning: "WARNING: invalid
>> page in block 2 of relation "base/16384/2608_fsm"; zeroing out page".
>> So clearly there's at least one bug somewhere.
>>
>> FWIW benchmarks showed a large improvement from backend and bgwriter
>> write combining, but I'll provide more detailed output from benchmarks
>> when I post a more reviewable patch set.
>>
>> 0001 and 0002 are completely independent cleanup that should be pushed
>> anyway, so I might do that, but I didn't want to do so without having
>> posted on the list at least once.
>>
>> - Melanie
>>
>
> A few comments for v14:
>
> 1 - 0001
> ```
> - FlushBuffer(buf, reln, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
> + FlushBuffer(buf, reln, io_object, io_context);
> ```
>
> This changes the hardcode IOOBJECT_RELATION to io_object when calling FlushBuffer(). But FlushBuffer() itself still uses IOOBJECT_RELATION instead of io_object, so the change will actually not take effective:
> ```
> pgstat_count_io_op_time(IOOBJECT_RELATION, io_context,
> IOOP_WRITE, io_start, 1, BLCKSZ);
> ```
>
> So, an update in FlushBuffer() is also needed.
>
> 2 - 0003 - freelist.c
> ```
> bool
> StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf, bool from_ring)
> {
> + Assert(strategy);
> +
> /* We only do this in bulkread mode */
> if (strategy->btype != BAS_BULKREAD)
> return false;
> @@ -795,8 +800,14 @@ StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf, bool from_r
> strategy->buffers[strategy->current] != BufferDescriptorGetBuffer(buf))
> return false;
>
> + Assert(BufferIsLockedByMe(BufferDescriptorGetBuffer(buf)));
> + Assert(!(pg_atomic_read_u64(&buf->state) & BM_LOCKED));
> ```
>
> I don’t quite understand Assert(!(pg_atomic_read_u64(&buf->state) & BM_LOCKED));
>
> The comment says “the buffer header spinlock must not be held,” but I doubt this Assert actually ensures that. Since BM_LOCKED is just a bit in a shared state, isn't it possible for a concurrent backend to grab the lock right when we’re checking it?
>
> If a concurrent process locks the header a split-second before the Assert, we’ll get a false-positive crash in a dev environment even though the code is fine. If they lock it a split-second after, then the Assert didn't really catch anything. It feels like a race condition either way.
>
> I think the only way to truly ensure a spinlock is "not held" is to actually acquire it. If we’re just checking the bit like this, it’s just a snapshot that might be stale by the time the instruction finishes. What was the specific worry here—a self-deadlock, or something else?
>
> 3 - 0004
> ```
> +typedef enum BufferUsageCountChange
> +{
> + BUC_ZERO,
> + BUC_MAX_ONE,
> + BUC_ONE,
> +} BufferUsageCountChange;
> ```
>
> Can we add some brief comments to explain every enum item? I feel hard to guess the meaning from the names without further reading the code.
>
> 4 - 0005 - bufmgr.c
> ```
> +/*
> + * Prepare bufdesc for eager flushing.
> + *
> + * Given bufnum, return the buffer descriptor of the buffer to eagerly flush,
> + * pinned and locked and with BM_IO_IN_PROGRESS set, or NULL if this buffer
> + * does not contain a block that should be flushed.
> + *
> + * If returning a buffer, also return its LSN.
> + */
> +static BufferDesc *
> +PrepareOrRejectEagerFlushBuffer(Buffer bufnum)
> ```
>
> This header comment looks stale.
>
> * It says “and with BM_IO_IN_PROGRESS set”, but I don’t see where BM_IO_IN_PROGRESS is set in this function.
> * It says “also return its LSN”, but I don’t see LSN is returned.
>
> 5 - 0006
> ```
> + /* Start IO on the first buffer */
> + if (!StartBufferIO(buf_hdr, false, false))
> + goto clean;
> ```
>
> This failure branch feels like leaking the content lock. The buffer was already share-locked via BufferLockConditional() earlier, and I don’t see the “clean" path unlock that content lock before returning.
>
> 6 - 0009
> ```
> + FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
> + UnpinBuffer(bufHdr);
> +
> + ScheduleBufferTagForWriteback(wb_context, IOCONTEXT_NORMAL, &bufHdr->tag);
> ```
>
> bufHdr is unlocked and unpinned, it might be unsafe to still use bufHdr->tag. I think we can copy bufHdr->tag to a local variable before unlock the buffer.
>
> ~~ My brain is stuck, I will continue 0010 tomorrow ~~
>
7 - 0010
```
- * batch_limit is the largest batch we are allowed to construct given the
- * remaining blocks in the table, the number of available pins, and the
- * current configuration.
+ * max_batch_size is the maximum number of blocks that can be combined into a
+ * single write in general. This function, based on the block number of start,
+ * will determine the maximum IO size for this particular write given how much
+ * of the file remains. max_batch_size is provided by the caller so it doesn't
+ * have to be recalculated for each write.
```
I don’t see the function FindStrategyFlushAdjacents() has a parameter named max_batch_size, but batch_limit is still there.
8 - 0010
```
static void
+FindFlushAdjacents(BufferDesc *batch_start,
+ uint32 batch_limit,
+ BufferWriteBatch *batch)
+{
+ BufferTag require; /* requested block's buffer tag */
+ uint32 newHash; /* hash value for require */
+ LWLock *newPartitionLock; /* buffer partition lock for it */
+ int buf_id;
+
+ /* create a tag so we can lookup the buffers */
+ InitBufferTag(&require, &batch->reln->smgr_rlocator.locator,
+ batch->forkno, InvalidBlockNumber);
+
+ for (; batch->n < batch_limit; batch->n++)
+ {
+ XLogRecPtr lsn;
+
+ require.blockNum = batch->start + batch->n;
+
+ Assert(BlockNumberIsValid(require.blockNum));
```
When I first time read the Assert, I was confused how it can assume the block to be valid, then I realized that WriteBatchInit() ensures a safe “limit”. Maybe add a brief comment for the Assert.
9 - 0010
```
+ batch->bufdescs[batch->n] =
+ PrepareOrRejectEagerFlushBuffer(buf_id + 1,
+ &require,
+ newPartitionLock,
+ &lsn);
+ if (lsn > batch->max_lsn)
+ batch->max_lsn = lsn;
+
+ if (batch->bufdescs[batch->n] == NULL)
+ break;
```
I think we can move if (batch->bufdescs[batch->n] == NULL) to before if (lsn > batch->max_lsn).
This is a correctness issue, because PrepareOrRejectEagerFlushBuffer will set lsn to InvalidXLogRecPtr when returns NULL, but doing the NULL check early just feels more reasonable.
10 - 0010
```
+ * max_lsn may be updated if the provided buffer LSN exceeds the current max
+ * LSN.
*/
static BufferDesc *
PrepareOrRejectEagerFlushBuffer(Buffer bufnum,
BufferTag *require,
+ LWLock *buftable_lock,
XLogRecPtr *lsn)
```
The function doesn’t have a parameter named max_lsn, is it “lsn”?
11 - 0010
```
+FindFlushAdjacents(BufferDesc *batch_start,
+ uint32 batch_limit,
+ BufferWriteBatch *batch)
```
Looks like batch_start is not used at all in this function.
12 - 0011
```
+ * Callers specify if and by how much they want to bump the buffer's usage
+ * count.
```
I don’t get what this comment means.
~~ As 0012 is WIP, I didn't review it. ~~
Best regards,
--
Chao Li (Evan)
HighGo Software Co., Ltd.
https://www.highgo.com/
Re: Checkpointer write combining
Attached is v15. I've done substantial work since my last post.
The biggest difference is that regular backends and background writer
write combining try to combine up to io_combine_limit sized write IOs
by looking for preceding and following blocks to their target block
that are in shared buffers and are dirty. I've found this to
substantially improve performance.
For a regular pgbench scale 500 with 8 clients and 4GB SB on a machine
with IOPS limited to 7500, pgbench TPS improves by 30% (I tuned
backend_flush_after to 512kB). I think in an environment where buffers
and IOPS are scarce, those extra buffers getting cleaned each time is
very helpful. It also improves the p99 latency by 75%. If you turn off
synchronous commit, it is actually almost a 70% increase in TPS
(because over 50% of the IO is WAL with sync commit on). In the stats
I collect, you see that with my patch backends and bgwriter are doing
larger writes and this is the source of the improvement.
I did several more realistic (than tpc-b) benchmarks -- including
multiple clients inserting 1000 rows at a time and saw similar
speedups. I isolated the different combining types and it seems that
the biggest benefit is coming from backends doing their own combining.
If you tune everything so the bgwriter is doing most of the cleaning
of buffers, there is still a benefit, but it is hard to get the
bgwriter sufficiently aggressive. checkpointer has little effect here
because the kernel was already combining those writes.
I did see some benefit in workloads with a fast, local SSD, but the
biggest benefit was in an IOPs constrained environment (which makes
sense). I'll note that I've lost the ability to reproduce the
performance gain with parallel COPY FROMs.
v15 also adds TAP tests of the write combining behavior.
I haven't enabled and started testing write combining for vacuum and bulkread.
The patchset still needs review and some polish. There are a number of
outstanding questions mostly around different function APIs and a bit
around some of the control flow.
I substantially refactored GetVictimBuffer() in
v15-0004-Simplify-victim-buffer-selection and
v15-0005-Refactor-victim-buffer-selection-and-add-helpers. I have
questions about some of the control flow changes I made including
whether or not we should keep looking in the strategy ring once we
find a buffer that has a usagecount > 1 (the current behavior in
master that I've preserved in my patch).
Another question is if EagerCleanStrategyBuffer() should change how it
advances the cursor to avoid calling PrepareOrRejectEagerFlushBuffer()
twice for a buffer that was rejected for reasons other than being
non-contiguous. I think that requirement worsens
PrepareOrRejectEagerFlushBuffer()'s API and potentially eliminate some
buffers we want to revisit, however without it, we may end up having
to reject the same buffers twice.
I've also incorporated Chao's review feedback. Here are my inline replies:
On Wed, Feb 25, 2026 at 1:53 AM Chao Li wrote:
>
> A few comments for v14:
Thanks for continuing to review!
> 1 - 0001
> ```
> - FlushBuffer(buf, reln, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
> + FlushBuffer(buf, reln, io_object, io_context);
> ```
>
> This changes the hardcode IOOBJECT_RELATION to io_object when calling FlushBuffer(). But FlushBuffer() itself still uses IOOBJECT_RELATION instead of io_object, so the change will actually not take effective:
> ```
> pgstat_count_io_op_time(IOOBJECT_RELATION, io_context,
> IOOP_WRITE, io_start, 1, BLCKSZ);
> ```
>
> So, an update in FlushBuffer() is also needed.
I believe we did already fix this. However, because FlushLocalBuffer()
exists, FlushBuffer() doesn't need to take an IOObject. And definitely
FlushUnlockedBuffer() does not need to -- since it takes an lock and
thus wouldn't be used for local buffers. I wonder if it is worth the
code churn to change these to avoid any confusion.
FlushRelationBuffers(), FlushRelationAllBuffers(),
FlushDatabaseBuffers(), and FlushOneBuffer(),
EvictUnpinnedBufferInternal() could stand to take an IOContext, though
they don't need it for their current callers, so I won't add the extra
code churn.
> 2 - 0003 - freelist.c
> ```
> bool
> StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf, bool from_ring)
> {
> + Assert(strategy);
> +
> /* We only do this in bulkread mode */
> if (strategy->btype != BAS_BULKREAD)
> return false;
> @@ -795,8 +800,14 @@ StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf, bool from_r
> strategy->buffers[strategy->current] != BufferDescriptorGetBuffer(buf))
> return false;
>
> + Assert(BufferIsLockedByMe(BufferDescriptorGetBuffer(buf)));
> + Assert(!(pg_atomic_read_u64(&buf->state) & BM_LOCKED));
> ```
>
> I don’t quite understand Assert(!(pg_atomic_read_u64(&buf->state) & BM_LOCKED));
>
> The comment says “the buffer header spinlock must not be held,” but I doubt this Assert actually ensures that. Since BM_LOCKED is just a bit in a shared state, isn't it possible for a concurrent backend to grab the lock right when we’re checking it?
>
> If a concurrent process locks the header a split-second before the Assert, we’ll get a false-positive crash in a dev environment even though the code is fine. If they lock it a split-second after, then the Assert didn't really catch anything. It feels like a race condition either way.
>
> I think the only way to truly ensure a spinlock is "not held" is to actually acquire it. If we’re just checking the bit like this, it’s just a snapshot that might be stale by the time the instruction finishes. What was the specific worry here—a self-deadlock, or something else?
I ended up changing StrategyRejectBuffer() substantially since then
and it no longer has this assert. However, this assert is more of a
sanity check. It is present for example in UnlockBufHdr().
> +typedef enum BufferUsageCountChange
> +{
> + BUC_ZERO,
> + BUC_MAX_ONE,
> + BUC_ONE,
> +} BufferUsageCountChange;
> ```
>
> Can we add some brief comments to explain every enum item? I feel hard to guess the meaning from the names without further reading the code.
Done
> +static BufferDesc *
> +PrepareOrRejectEagerFlushBuffer(Buffer bufnum)
> ```
>
> This header comment looks stale.
>
> * It says “and with BM_IO_IN_PROGRESS set”, but I don’t see where BM_IO_IN_PROGRESS is set in this function.
> * It says “also return its LSN”, but I don’t see LSN is returned.
Fixed
> + /* Start IO on the first buffer */
> + if (!StartBufferIO(buf_hdr, false, false))
> + goto clean;
> ```
>
> This failure branch feels like leaking the content lock. The buffer was already share-locked via BufferLockConditional() earlier, and I don’t see the “clean" path unlock that content lock before returning.
I think I've found and fixed anything like this.
> + FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
> + UnpinBuffer(bufHdr);
> +
> + ScheduleBufferTagForWriteback(wb_context, IOCONTEXT_NORMAL, &bufHdr->tag);
> ```
>
> bufHdr is unlocked and unpinned, it might be unsafe to still use bufHdr->tag. I think we can copy bufHdr->tag to a local variable before unlock the buffer.
Fixed.
On Wed, Feb 25, 2026 at 11:24 PM Chao Li wrote:
>
> - * batch_limit is the largest batch we are allowed to construct given the
> - * remaining blocks in the table, the number of available pins, and the
> - * current configuration.
> + * max_batch_size is the maximum number of blocks that can be combined into a
> + * single write in general. This function, based on the block number of start,
> + * will determine the maximum IO size for this particular write given how much
> + * of the file remains. max_batch_size is provided by the caller so it doesn't
> + * have to be recalculated for each write.
> ```
>
> I don’t see the function FindStrategyFlushAdjacents() has a parameter named max_batch_size, but batch_limit is still there.
Fixed.
> static void
> +FindFlushAdjacents(BufferDesc *batch_start,
> + uint32 batch_limit,
> + BufferWriteBatch *batch)
> +{
> + BufferTag require; /* requested block's buffer tag */
> + uint32 newHash; /* hash value for require */
> + LWLock *newPartitionLock; /* buffer partition lock for it */
> + int buf_id;
> +
> + /* create a tag so we can lookup the buffers */
> + InitBufferTag(&require, &batch->reln->smgr_rlocator.locator,
> + batch->forkno, InvalidBlockNumber);
> +
> + for (; batch->n < batch_limit; batch->n++)
> + {
> + XLogRecPtr lsn;
> +
> + require.blockNum = batch->start + batch->n;
> +
> + Assert(BlockNumberIsValid(require.blockNum));
> ```
>
> When I first time read the Assert, I was confused how it can assume the block to be valid, then I realized that WriteBatchInit() ensures a safe “limit”. Maybe add a brief comment for the Assert.
Added comment.
> + batch->bufdescs[batch->n] =
> + PrepareOrRejectEagerFlushBuffer(buf_id + 1,
> + &require,
> + newPartitionLock,
> + &lsn);
> + if (lsn > batch->max_lsn)
> + batch->max_lsn = lsn;
> +
> + if (batch->bufdescs[batch->n] == NULL)
> + break;
> ```
>
> I think we can move if (batch->bufdescs[batch->n] == NULL) to before if (lsn > batch->max_lsn).
>
> This is a correctness issue, because PrepareOrRejectEagerFlushBuffer will set lsn to InvalidXLogRecPtr when returns NULL, but doing the NULL check early just feels more reasonable.
Fixed.
> + * max_lsn may be updated if the provided buffer LSN exceeds the current max
> + * LSN.
> */
> static BufferDesc *
> PrepareOrRejectEagerFlushBuffer(Buffer bufnum,
> BufferTag *require,
> + LWLock *buftable_lock,
> XLogRecPtr *lsn)
> ```
>
> The function doesn’t have a parameter named max_lsn, is it “lsn”?
Fixed.
> +FindFlushAdjacents(BufferDesc *batch_start,
> + uint32 batch_limit,
> + BufferWriteBatch *batch)
> ```
>
> Looks like batch_start is not used at all in this function.
>
> 12 - 0011
> ```
> + * Callers specify if and by how much they want to bump the buffer's usage
> + * count.
> ```
>
> I don’t get what this comment means.
I removed it.
On Fri, Jan 23, 2026 at 7:17 AM Soumya S Murali
wrote:
>
> Batch size = 8
> LOG: checkpoint complete: wrote 12622 buffers (77.0%); write=0.113 s,
> sync=0.195 s, total=0.485 s; sync files=37
> DEBUG: checkpoint BufferSync stats: buffers_written=9923, writeback_calls=1242
> Avg: 7.989 approx 8 buffers per writeback.
>
> Batch size = 16
> LOG: checkpoint complete: wrote 13537 buffers (82.6%); write=0.260 s,
> sync=0.211 s, total=0.625 s; sync files=3
> DEBUG: checkpoint BufferSync stats: buffers_written=6196, writeback_calls=389
> Avg: 15.9 approx 16 buffers per writeback.
>
> Batch size = 32
> LOG: checkpoint complete: wrote 12914 buffers (78.8%); write=0.116 s,
> sync=0.136 s, total=0.442 s; sync files=5
> DEBUG: checkpoint BufferSync stats: buffers_written=12914, writeback_calls=1616
> Avg: 7.99 approx 8 buffers per writeback.
>
> Batch 16 significantly reduces sync fan-out (as low as 3 files per
> checkpoint), but this comes at the cost of longer individual sync
> operations, resulting in higher total checkpoint time (≈0.625 s).
> Batch 32 provides a better balance, maintaining low sync fragmentation
> while avoiding long sync stalls, yielding the lowest overall
> checkpoint time (≈0.442 s). I am attaching the patch with batch size
> fixed as 32 for now for further review.
> Please let me know if further workloads or instrumentation would be useful.
FWIW, I found batch size 16 to be optimal in experimenting with my own
patchset as well.
- Melanie
Re: Checkpointer write combining
> On 20 Jun 2026, at 03:13, Melanie Plageman wrote:
>
> Attached is v15
Hi Melanie,
I started reviewing the write-combining series and want to send feedback in
groups. This first group covers the preparatory/refactor patches that come
before any actual write combining: the ScheduleBufferTagForWriteback
cleanup, the pg_stat_io fix, the StrategyRejectBuffer/PinBuffer tweaks, and
the two victim-buffer-selection refactors.
Per-patch
=========
* "Make ScheduleBufferTagForWriteback static"
LGTM as a preparatory cleanup. Note that a later patch in the series
("Write combining for background writer") removes the function entirely.
So this intermediate static-ification is churn that goes away.
* "pg_stat_io: Count buffer eviction after invalidation"
This is a bug fix. Is it too insignificant for backpatching?
* "Make StrategyRejectBuffer encapsulate more logic"
I agree that there's no need to check from_ring in StrategyRejectBuffer().
Assert(strategy) documents it well.
Non-rejection of not-BM_PERMANENT and not needing WAL flush is a bit mind
melting due to lots of negations.
But it seems correct new heuristic. Maybe it is already in effect somewhere
else in the code, IDK.
Moving BufHdrGetBlock()/BufferGetLSN() into buf_internals.h is reasonable.
"shared buffers only" macro is now visible to more code, so it's a bit easier
to misuse on a local buffer. Not something worth bothering, just maybe Assert
somewhere... But it's fine as is.
* "Simplify victim buffer selection"
This is the big one and I think the direction is right: ClaimVictimBuffer()
loop is much easier to follow than the old goto-again control flow.
The commit message is commendably explicit about the three behavior
changes. It seems to me they're all improvements, and not adding a shared
buffer to the ring until it's fully claimed is clearly better.
These changes only matter under contention, so an experiment would be good.
I imagine something like: run several concurrent COPY FROMs (a contended
BAS_BULKWRITE workload) and compare pg_stat_io in the "bulkwrite" context
before and after the patch. The number to watch is reuses vs evictions.
If evictions go up noticeably, the strategy is giving up on its ring and
evicting from shared buffers more than before, which would work against the
ring's whole point of not polluting the buffer pool. If the ratio stays
about the same, the behavior change is harmless. I'll try to allocate time
to do this check myself, if you think such experiment is of an interest.
On your XXX ("should we keep looking in the ring when a buffer can't be
reused due to usage/pin count, instead of going to shared buffers?"): my
vote is to keep the simpler "go to the clocksweep" behavior. Re-scanning
the ring for a hot/pinned slot risks spinning on the same busy buffers,
and replacing the slot from the clocksweep is what master effectively does
today anyway.
One modular note: ClaimVictimBuffer() now performs I/O (FlushBuffer and
potentially XLogFlush) but is called from the freelist.c selection
helpers, and it's declared "For use in freelist.c but defined in bufmgr.c".
That blurs the old freelist.c (pure selection) / bufmgr.c (I/O) boundary a
bit. I'm not sure such convention exists, but anyway.
This patch folds buffer claiming into the existing StrategyGetBuffer() (so
it now both selects and claims a victim), and the very next patch then
splits StrategyGetBuffer() into GetBufferFromRing()/GetBufferFromClocksweep().
So this intermediate shape doesn't survive.
* "Refactor victim buffer selection and add helpers"
I like API with which this patch ends. GetBufferFromRing()/
GetBufferFromClocksweep() are much clearer than the old StrategyGetBuffer(),
and dropping the redundant "strategy &&" in front of from_ring seems correct.
The duplicated buf_valid + EVICT/REUSE counting between the
two helpers is the small price you declare in the message. I think that's
acceptable, though a tiny static helper for "count and return" could remove.
* "Allow PinBuffer to skip increasing usage count"
LGTM. Made me look at where usage_count actually climbs. Always +1,
capped at BM_MAX_USAGE_COUNT (5). nbtree re-pins internal pages (a splitting
insert re-pins the parent). Expected enough, the cap is just small, so those
pages sit at max.
The BufferUsageCountChange enum is more readable than the old
strategy==NULL overloading. BUC_ZERO is unused here (introduced for later
patches), which is fine to mention in the message. Two tiny nits: BUC_ONE
vs BUC_MAX_ONE are easy to mix up at a glance, and the
"strategy ? BUC_MAX_ONE : BUC_ONE" mapping is now repeated at three call
sites. A one-line helper or a comment on the enum would help.
I didn't find any correctness problems in this group. The buf_valid
staleness handling and the conditional-lock/reject/invalidate ordering
all look correct to me.
Design-level questions (looking ahead at patches not reviewed yet)
==================================================================
* eager_clean_max_batch_size vs io_combine_limit. I realize the batch-size
sizing has been discussed at length already, and I couldn't tell what was
finally settled, so treat this as a DBA-side note. In the code, eager
cleaning is already bounded by io_combine_limit (MaxWriteBatchSize), and
eager_clean_max_batch_size is an additional cap on top of that
(CurrentMaxEagerWriteBatchSize). That only becomes clear after reading
bufmgr.c. From the docs and postgresql.conf alone it does not: io_combine_limit
reads fine, but eager_clean_max_batch_size gives no hint of which "cleaning"
it means, or why it needs a separate knob next to io_combine_limit. If it
survives (the commit notes "XXX: remove development-only GUCs"), the
docs should spell out how it relates to io_combine_limit.
* Batch construction geometry. The strategy path only looks forward from the
target buffer, while the client-backend/bgwriter path looks both ways
around the target block. Isn't forward-only case leaving easy combining
on the table?
I'll follow up with the bulkwrite and checkpointer patches next.
Best regards, Andrey Borodin.
Re: Checkpointer write combining
On Sat, Jun 20, 2026 at 6:13 AM Melanie Plageman <melanieplageman@gmail.com> wrote:
>
> Attached is v15. I've done substantial work since my last post.
>
> The biggest difference is that regular backends and background writer
> write combining try to combine up to io_combine_limit sized write IOs
> by looking for preceding and following blocks to their target block
> that are in shared buffers and are dirty. I've found this to
> substantially improve performance.
>
> For a regular pgbench scale 500 with 8 clients and 4GB SB on a machine
> with IOPS limited to 7500, pgbench TPS improves by 30% (I tuned
> backend_flush_after to 512kB). I think in an environment where buffers
> and IOPS are scarce, those extra buffers getting cleaned each time is
> very helpful. It also improves the p99 latency by 75%. If you turn off
> synchronous commit, it is actually almost a 70% increase in TPS
> (because over 50% of the IO is WAL with sync commit on). In the stats
> I collect, you see that with my patch backends and bgwriter are doing
> larger writes and this is the source of the improvement.
>
> I did several more realistic (than tpc-b) benchmarks -- including
> multiple clients inserting 1000 rows at a time and saw similar
> speedups. I isolated the different combining types and it seems that
> the biggest benefit is coming from backends doing their own combining.
> If you tune everything so the bgwriter is doing most of the cleaning
> of buffers, there is still a benefit, but it is hard to get the
> bgwriter sufficiently aggressive. checkpointer has little effect here
> because the kernel was already combining those writes.
>
> I did see some benefit in workloads with a fast, local SSD, but the
> biggest benefit was in an IOPs constrained environment (which makes
> sense). I'll note that I've lost the ability to reproduce the
> performance gain with parallel COPY FROMs.
>
> v15 also adds TAP tests of the write combining behavior.
>
> I haven't enabled and started testing write combining for vacuum and bulkread.
>
> The patchset still needs review and some polish. There are a number of
> outstanding questions mostly around different function APIs and a bit
> around some of the control flow.
>
> I substantially refactored GetVictimBuffer() in
> v15-0004-Simplify-victim-buffer-selection and
> v15-0005-Refactor-victim-buffer-selection-and-add-helpers. I have
> questions about some of the control flow changes I made including
> whether or not we should keep looking in the strategy ring once we
> find a buffer that has a usagecount > 1 (the current behavior in
> master that I've preserved in my patch).
>
> Another question is if EagerCleanStrategyBuffer() should change how it
> advances the cursor to avoid calling PrepareOrRejectEagerFlushBuffer()
> twice for a buffer that was rejected for reasons other than being
> non-contiguous. I think that requirement worsens
> PrepareOrRejectEagerFlushBuffer()'s API and potentially eliminate some
> buffers we want to revisit, however without it, we may end up having
> to reject the same buffers twice.
>
> I've also incorporated Chao's review feedback. Here are my inline replies:
>
> On Wed, Feb 25, 2026 at 1:53 AM Chao Li <li.evan.chao@gmail.com> wrote:
> >
> > A few comments for v14:
>
> Thanks for continuing to review!
>
> > 1 - 0001
> > ```
> > - FlushBuffer(buf, reln, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
> > + FlushBuffer(buf, reln, io_object, io_context);
> > ```
> >
> > This changes the hardcode IOOBJECT_RELATION to io_object when calling FlushBuffer(). But FlushBuffer() itself still uses IOOBJECT_RELATION instead of io_object, so the change will actually not take effective:
> > ```
> > pgstat_count_io_op_time(IOOBJECT_RELATION, io_context,
> > IOOP_WRITE, io_start, 1, BLCKSZ);
> > ```
> >
> > So, an update in FlushBuffer() is also needed.
>
> I believe we did already fix this. However, because FlushLocalBuffer()
> exists, FlushBuffer() doesn't need to take an IOObject. And definitely
> FlushUnlockedBuffer() does not need to -- since it takes an lock and
> thus wouldn't be used for local buffers. I wonder if it is worth the
> code churn to change these to avoid any confusion.
>
> FlushRelationBuffers(), FlushRelationAllBuffers(),
> FlushDatabaseBuffers(), and FlushOneBuffer(),
> EvictUnpinnedBufferInternal() could stand to take an IOContext, though
> they don't need it for their current callers, so I won't add the extra
> code churn.
>
> > 2 - 0003 - freelist.c
> > ```
> > bool
> > StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf, bool from_ring)
> > {
> > + Assert(strategy);
> > +
> > /* We only do this in bulkread mode */
> > if (strategy->btype != BAS_BULKREAD)
> > return false;
> > @@ -795,8 +800,14 @@ StrategyRejectBuffer(BufferAccessStrategy strategy, BufferDesc *buf, bool from_r
> > strategy->buffers[strategy->current] != BufferDescriptorGetBuffer(buf))
> > return false;
> >
> > + Assert(BufferIsLockedByMe(BufferDescriptorGetBuffer(buf)));
> > + Assert(!(pg_atomic_read_u64(&buf->state) & BM_LOCKED));
> > ```
> >
> > I don’t quite understand Assert(!(pg_atomic_read_u64(&buf->state) & BM_LOCKED));
> >
> > The comment says “the buffer header spinlock must not be held,” but I doubt this Assert actually ensures that. Since BM_LOCKED is just a bit in a shared state, isn't it possible for a concurrent backend to grab the lock right when we’re checking it?
> >
> > If a concurrent process locks the header a split-second before the Assert, we’ll get a false-positive crash in a dev environment even though the code is fine. If they lock it a split-second after, then the Assert didn't really catch anything. It feels like a race condition either way.
> >
> > I think the only way to truly ensure a spinlock is "not held" is to actually acquire it. If we’re just checking the bit like this, it’s just a snapshot that might be stale by the time the instruction finishes. What was the specific worry here—a self-deadlock, or something else?
>
> I ended up changing StrategyRejectBuffer() substantially since then
> and it no longer has this assert. However, this assert is more of a
> sanity check. It is present for example in UnlockBufHdr().
>
> > +typedef enum BufferUsageCountChange
> > +{
> > + BUC_ZERO,
> > + BUC_MAX_ONE,
> > + BUC_ONE,
> > +} BufferUsageCountChange;
> > ```
> >
> > Can we add some brief comments to explain every enum item? I feel hard to guess the meaning from the names without further reading the code.
>
> Done
>
> > +static BufferDesc *
> > +PrepareOrRejectEagerFlushBuffer(Buffer bufnum)
> > ```
> >
> > This header comment looks stale.
> >
> > * It says “and with BM_IO_IN_PROGRESS set”, but I don’t see where BM_IO_IN_PROGRESS is set in this function.
> > * It says “also return its LSN”, but I don’t see LSN is returned.
>
> Fixed
>
> > + /* Start IO on the first buffer */
> > + if (!StartBufferIO(buf_hdr, false, false))
> > + goto clean;
> > ```
> >
> > This failure branch feels like leaking the content lock. The buffer was already share-locked via BufferLockConditional() earlier, and I don’t see the “clean" path unlock that content lock before returning.
>
> I think I've found and fixed anything like this.
>
> > + FlushUnlockedBuffer(bufHdr, NULL, IOOBJECT_RELATION, IOCONTEXT_NORMAL);
> > + UnpinBuffer(bufHdr);
> > +
> > + ScheduleBufferTagForWriteback(wb_context, IOCONTEXT_NORMAL, &bufHdr->tag);
> > ```
> >
> > bufHdr is unlocked and unpinned, it might be unsafe to still use bufHdr->tag. I think we can copy bufHdr->tag to a local variable before unlock the buffer.
>
> Fixed.
>
> On Wed, Feb 25, 2026 at 11:24 PM Chao Li <li.evan.chao@gmail.com> wrote:
> >
> > - * batch_limit is the largest batch we are allowed to construct given the
> > - * remaining blocks in the table, the number of available pins, and the
> > - * current configuration.
> > + * max_batch_size is the maximum number of blocks that can be combined into a
> > + * single write in general. This function, based on the block number of start,
> > + * will determine the maximum IO size for this particular write given how much
> > + * of the file remains. max_batch_size is provided by the caller so it doesn't
> > + * have to be recalculated for each write.
> > ```
> >
> > I don’t see the function FindStrategyFlushAdjacents() has a parameter named max_batch_size, but batch_limit is still there.
>
> Fixed.
>
> > static void
> > +FindFlushAdjacents(BufferDesc *batch_start,
> > + uint32 batch_limit,
> > + BufferWriteBatch *batch)
> > +{
> > + BufferTag require; /* requested block's buffer tag */
> > + uint32 newHash; /* hash value for require */
> > + LWLock *newPartitionLock; /* buffer partition lock for it */
> > + int buf_id;
> > +
> > + /* create a tag so we can lookup the buffers */
> > + InitBufferTag(&require, &batch->reln->smgr_rlocator.locator,
> > + batch->forkno, InvalidBlockNumber);
> > +
> > + for (; batch->n < batch_limit; batch->n++)
> > + {
> > + XLogRecPtr lsn;
> > +
> > + require.blockNum = batch->start + batch->n;
> > +
> > + Assert(BlockNumberIsValid(require.blockNum));
> > ```
> >
> > When I first time read the Assert, I was confused how it can assume the block to be valid, then I realized that WriteBatchInit() ensures a safe “limit”. Maybe add a brief comment for the Assert.
>
> Added comment.
>
> > + batch->bufdescs[batch->n] =
> > + PrepareOrRejectEagerFlushBuffer(buf_id + 1,
> > + &require,
> > + newPartitionLock,
> > + &lsn);
> > + if (lsn > batch->max_lsn)
> > + batch->max_lsn = lsn;
> > +
> > + if (batch->bufdescs[batch->n] == NULL)
> > + break;
> > ```
> >
> > I think we can move if (batch->bufdescs[batch->n] == NULL) to before if (lsn > batch->max_lsn).
> >
> > This is a correctness issue, because PrepareOrRejectEagerFlushBuffer will set lsn to InvalidXLogRecPtr when returns NULL, but doing the NULL check early just feels more reasonable.
>
> Fixed.
>
> > + * max_lsn may be updated if the provided buffer LSN exceeds the current max
> > + * LSN.
> > */
> > static BufferDesc *
> > PrepareOrRejectEagerFlushBuffer(Buffer bufnum,
> > BufferTag *require,
> > + LWLock *buftable_lock,
> > XLogRecPtr *lsn)
> > ```
> >
> > The function doesn’t have a parameter named max_lsn, is it “lsn”?
>
> Fixed.
>
> > +FindFlushAdjacents(BufferDesc *batch_start,
> > + uint32 batch_limit,
> > + BufferWriteBatch *batch)
> > ```
> >
> > Looks like batch_start is not used at all in this function.
> >
> > 12 - 0011
> > ```
> > + * Callers specify if and by how much they want to bump the buffer's usage
> > + * count.
> > ```
> >
> > I don’t get what this comment means.
>
> I removed it.
>
> On Fri, Jan 23, 2026 at 7:17 AM Soumya S Murali
> <soumyamurali.work@gmail.com> wrote:
> >
> > Batch size = 8
> > LOG: checkpoint complete: wrote 12622 buffers (77.0%); write=0.113 s,
> > sync=0.195 s, total=0.485 s; sync files=37
> > DEBUG: checkpoint BufferSync stats: buffers_written=9923, writeback_calls=1242
> > Avg: 7.989 approx 8 buffers per writeback.
> >
> > Batch size = 16
> > LOG: checkpoint complete: wrote 13537 buffers (82.6%); write=0.260 s,
> > sync=0.211 s, total=0.625 s; sync files=3
> > DEBUG: checkpoint BufferSync stats: buffers_written=6196, writeback_calls=389
> > Avg: 15.9 approx 16 buffers per writeback.
> >
> > Batch size = 32
> > LOG: checkpoint complete: wrote 12914 buffers (78.8%); write=0.116 s,
> > sync=0.136 s, total=0.442 s; sync files=5
> > DEBUG: checkpoint BufferSync stats: buffers_written=12914, writeback_calls=1616
> > Avg: 7.99 approx 8 buffers per writeback.
> >
> > Batch 16 significantly reduces sync fan-out (as low as 3 files per
> > checkpoint), but this comes at the cost of longer individual sync
> > operations, resulting in higher total checkpoint time (≈0.625 s).
> > Batch 32 provides a better balance, maintaining low sync fragmentation
> > while avoiding long sync stalls, yielding the lowest overall
> > checkpoint time (≈0.442 s). I am attaching the patch with batch size
> > fixed as 32 for now for further review.
> > Please let me know if further workloads or instrumentation would be useful.
>
> FWIW, I found batch size 16 to be optimal in experimenting with my own
> patchset as well.
>
> - Melanie
Hi Melanie,
I have been looking through the v15 series. The current implementation looks fairly complete for synchronous shared-buffer write combining, but I have a few questions about whether the API shape is general enough for the longer-term AIO and direct-I/O goals.
1. Submission and completion lifetime
BufferWriteBatch is currently stack-allocated and contains pinned, content-locked buffer descriptors. FlushBufferBatch() then performs WAL flushing, checksum preparation, synchronous smgrwritev(), and I/O accounting, after which CompleteWriteBatchIO() marks the buffers clean.
That works well for synchronous writes, but it seems to encode an all-or-nothing synchronous lifetime.
For an asynchronous implementation:
* How would the batch object survive after submission?
* Would all pins and content locks remain held until completion?
* Would submission, completion, and cleanup need to become separate phases?
For example, would an interface along these lines make the lifetime clearer?
* PrepareBufferWriteBatch()
* SubmitBufferWriteBatch()
* CompleteBufferWriteBatch()
* AbortBufferWriteBatch()
The current implementation could still complete synchronously inside SubmitBufferWriteBatch(), but the interface would not require that behavior.
2. Failure and partial completion
The current path appears to assume that normal return from smgrwritev() means that the whole batch completed successfully, after which all buffers can be marked clean.
Would the future API need to represent:
* partial completion,
* cancellation,
* submission failure,
* or an error affecting only part of a batch?
Even if the current smgr contract remains all-or-nothing, it may be useful to make that contract explicit rather than embedding it in FlushBufferBatch().
3. Relationship with the read side
Write combining is important for direct I/O, but the same applies to reads. Issuing one 8 kB direct-I/O request per buffer would also lose the readahead and aggregation normally provided by the kernel page cache.
I do not think the read and write buffer state machines necessarily need to share the same API, since their locking and completion rules are quite different.
However, could the lower-level physical-I/O parts be read/write neutral?
For example:
* contiguous extent description,
* io_combine_limit,
* smgr segment and boundary handling,
* multi-block submission,
* completion representation,
* and physical-I/O accounting.
Otherwise, is there a risk that the write-batching code and the read-side AIO infrastructure evolve into two parallel mechanisms for essentially the same physical-I/O aggregation problem?
4. Foreground backend work and lock duration
For foreground backends, combining a required victim with several adjacent buffers increases more than just the I/O size; it can introduce unpredictable latency spikes for user queries. It also increases:
* the amount of foreground cleanup work,
* the number of pinned buffers,
* and the time for which content locks may be held.
Should foreground batching therefore have a separate latency or work budget, in addition to the pin limit and maximum combine size?
My main concern is that, without separating these layers now, asynchronous writes may require another substantial API refactoring later.
Thanks,
Haibo
Re: Checkpointer write combining
> On 19 Jul 2026, at 11:05, Andrey Borodin wrote: > > I'll follow up with the bulkwrite and checkpointer patches next. Hi! I looked through 0007-0009 and did not find correctness issues. The existing COPY test uses an unlogged relation, so it does not exercise the WAL eligibility checks in PrepareOrRejectEagerFlushBuffer(). I tried the same test with a regular table and it consistently combined writes. For deterministic results I used wal_writer_delay = '10ms'. With synchronous_commit disabled, a fast COPY may otherwise finish before the default 200ms WAL writer interval. fsync can remain disabled: the test only needs the PostgreSQL WAL flush position to advance. Perhaps the test could run the COPY case for both unlogged and regular tables. Best regards, Andrey Borodin.
Re: Checkpointer write combining
On Mon, Jul 20, 2026 at 6:21 PM Haibo Yan wrote: > > I have been looking through the v15 series. Thanks for taking a look. > The current implementation looks fairly complete for synchronous shared-buffer write combining, but I have a few questions about whether the API shape is general enough for the longer-term AIO and direct-I/O goals. > 1. Submission and completion lifetime > BufferWriteBatch is currently stack-allocated and contains pinned, content-locked buffer descriptors. FlushBufferBatch() then performs WAL flushing, checksum preparation, synchronous smgrwritev(), and I/O accounting, after which CompleteWriteBatchIO() marks the buffers clean. > That works well for synchronous writes, but it seems to encode an all-or-nothing synchronous lifetime. Reads use AIO and have an object in backend memory ReadBuffersOperation. When other backends complete a read, there are a limited number of things that they have to do in the shared callback and they can use a PgAIOHandle to do it. The issuing backend still needs access to information outside of what is in the PgAIOHandle (and has a different lifetime), and it gets that with the ReadBuffersOperation. Writes are similar with a few differences, but they will need a dedicated object for the issuing backend to keep track of the operations it initiates. In my latest posted version (v16 [1]), I renamed BufferWriteBatch to WriteBuffersOperation to make it more symmetrical. > For an asynchronous implementation: > > * How would the batch object survive after submission? In the issuing backend which has responsibilities like adding the buffers to the writeback queue after completion. > * Would all pins and content locks remain held until completion? They have to be or someone could corrupt the buffer while it was being written out. > * Would submission, completion, and cleanup need to become separate phases? There will have to be three-ish functions -- one to start the writes in an issuing backend, one to complete the writes in either the issuing backend or another backend, and one to wait for the writes to be done and do any remaining tasks on the buffers. In v16 [1], I've renamed FlushBufferBatch() to WriteBuffers() and CompleteBufferBatchIO() to CompleteWriteBuffers(). With AIO, those will have to become StartWriteBuffers() and WaitWriteBuffers() with a separate completion callback implemented. I had an LLM demonstrate what AIO writes would look like on top of write combining. I looked at the commits it wrote and they have some problems and are missing some things (including not handling some architectural issues that Andres has already mentioned we have to solve before implementing AIO writes) -- but the broad strokes are correct and I think that is the shape we'll end up with [2]. Doing this exercise helped me figure out what to name functions and if I needed to change anything for future-proofing reasons. > 2. Failure and partial completion > The current path appears to assume that normal return from smgrwritev() means that the whole batch completed successfully, after which all buffers can be marked clean. > Would the future API need to represent: > > * partial completion, > * cancellation, > * submission failure, > * or an error affecting only part of a batch? Yes, it would but that code is non-trivial and not needed with a single combined write as smgrwritev() will complete or fail -- there won't be partial writes. I have some of the above in the hack-y AIO writes branch I mentioned and I don't think any of those considerations change the shape of the code in a way that merits changing synchronous combining. > Even if the current smgr contract remains all-or-nothing, it may be useful to make that contract explicit rather than embedding it in FlushBufferBatch(). I don't know what you mean by this. > 3. Relationship with the read side > Write combining is important for direct I/O, but the same applies to reads. Issuing one 8 kB direct-I/O request per buffer would also lose the readahead and aggregation normally provided by the kernel page cache. > I do not think the read and write buffer state machines necessarily need to share the same API, since their locking and completion rules are quite different. > However, could the lower-level physical-I/O parts be read/write neutral? > For example: > > * contiguous extent description, > * io_combine_limit, > * smgr segment and boundary handling, > * multi-block submission, > * completion representation, > * and physical-I/O accounting. io_combine_limit is already what is used for writes in my code. I had a development-only guc letting me control it separately but I got rid of that in v16. The boundary handling can't work the same way as reads because reads only read ahead and don't consider going backwards to create a batch (wouldn't make sense). And for buffer access strategy, it works differently as well with writes. The completion callbacks will look similar but can't be shared because you have different things you need to do on completion. All of the low-level IO stuff will be shared, but at the bufmgr layer, not much issuing/completing code can be shared, as it's not the same behavior (flushing WAL, locks, fsync requests, writeback requests, etc). And I/O accounting at bufmgr level has always been done with separate traces and pg_stat_io function calls for reads and writes. > Those pieces seem closely related to what the recent ReadStream work and the broader AIO effort already need > Otherwise, is there a risk that the write-batching code and the read-side AIO infrastructure evolve into two parallel mechanisms for essentially the same physical-I/O aggregation problem? I have made an effort to make the structures and names more consistent with the Read concepts in v16 -- including moving from BufferDescriptors to Buffers in the WriteBuffersOperation. > 4. Foreground backend work and lock duration > For foreground backends, combining a required victim with several adjacent buffers increases more than just the I/O size; it can introduce unpredictable latency spikes for user queries. It also increases: > > * the amount of foreground cleanup work, > * the number of pinned buffers, > * and the time for which content locks may be held. > > Should foreground batching therefore have a separate latency or work budget, in addition to the pin limit and maximum combine size? Number of pinned buffers is already bounded by io_combine_limit and eventually by effective_io_concurrency -- like reads. I think that is sufficient with only write combining. Once we have AIO writes, there will be much more competition for pinned buffers (since we have reads already), so perhaps we will need to think about the pinned buffers limits, but I don't foresee any issue with non-toy shared buffers with just write combining. As for foreground cleanup work and content lock duration, if there is enough shared buffer pressure that you are evicting buffers at all (which is the only time you'll do this combining for regular backends), then the buffers you are eagerly cleaning will need to be cleaned by someone. Combining won't create new writes, only change how they're issued. And if there isn't shared buffer pressure, it is less likely that you are I/O bound. However, there is a possible negative case here I describe in my most recent performance analysis here [1] (see the section entitled "Mixed buffer hits leading to non-contiguous rings"). If your point is that a 128kB write takes longer than an 8kB write, sure, that's usually true (though if you flood the device with enough small requests, you may end up having the 8kB write take longer). However, the aggregate time spent holding locks will go down with write combining. If you write out 16 8k blocks individually, each one pays the full per-write cost -- making the aggregate time spent holding locks much higher than writing a single 128k write. Now if all the concurrently working backends are contending for the lock on the buffers that are being written out in that 128k write, you can see p999 latency spikes occasionally -- and I did see that in a scenario I concocted to exercise this. But the more common case is that in IOPs constrained environments, the p99 latency with combining can improve by 80%+. The writes being done by regular backends and background writer are random IO without combining, so making them more sequential relieves a lot of IOPs pressure. Separately, there is a cost to doing a few more buffer table lookups, but I did performance evaluation and, even in the worst case, it seems to have basically no impact given the cost of writing. I think once we can issue more than one combined IO (with AIO) then we have to be way more careful of this stuff. Backends absolutely can't wait for multiple IOs to finish when their victim was in the first IO -- even if the IOs are overlapped with AIO. And we'll have to be worried about putting too much IO in flight. > My main concern is that, without separating these layers now, asynchronous writes may require another substantial API refactoring later. Yes, we want to avoid that, but I think with the latest revisions, we are being as careful as we can reasonably be. - Melanie [1] https://www.postgresql.org/message-id/CAAKRu_Z%2BGEgkHqQPajsy0ApDWYTvfmR5G6AjnE7mVcy1_00kxQ%40mail.gmail.com [2] https://github.com/melanieplageman/postgres/tree/aio_writes_llm-draft (I will likely delete this branch later, sorry to anyone looking at this in the hackers archive)
Re: Checkpointer write combining
Thanks for working on this. I tried v16 and have a few notes.
1. Recovery from a base backup crashes for me on an assert build.
On master I get
WARNING: xlog min recovery request 0/045E5260 is past current
point 0/0210CF08
CONTEXT: writing block 0 of relation "base/5/16384_vm"
and recovery finishes. With v16 the startup process then hits
TRAP: failed Assert("... || !XLogNeedsFlush(BufferGetLSN(bufhdr))")
I think it is because XLogFlush() only warns in this case, so the
new Assert in WriteBuffers() does not hold in recovery. It needs
checksums off.
takes 26.3s on master and 11.2s with v16. With the attached patch it
is 26.7s.
pgbench at scale 100 and 256MB shared_buffers, the bgwriter hits the
limit in most rounds on both. In 60s it cleaned 28000 clock hand
buffers on master and 20218 with v16. tps was about the same. Is
that intended? I also wonder if the bgwriter falls behind the clock sweep more
write, so the clock tick may pass it in the middle of a round. I did not
test this yet but I think worth to discuss.
batch. With EIO on block 690, the retry also logs "write error might
be permanent" for 691 and 692. I think technically we can do better but
5. 0004 renames buffer-sync-written, but monitoring.sgml still has
probes can wait until the functional parts are done.
Thanks,