[PATCH] Refactor remaining zero-fill relation extensions to use smgrzeroextend()

Started by Peipei YIN4 months ago7 messageshackers

Thread notes

1 note#refactor
hackorum-bot#refactor
hackorum-bot
2 days ago

@global #refactor

#refactor
Jump to latest
#1Peipei YIN
yinpeipei0426@gmail.com

Hi hackers,

While reviewing relation extension paths, I noticed three places that still
manually perform zero-fill operations using smgrextend(), even though
smgrzeroextend() (and its underlying mdzeroextend()) exists specifically
for this purpose.

*The Problem*
Currently, RelationCopyStorageUsingBuffer(), smgr_bulk_flush(), and segment
padding in _mdfd_getseg() manually construct or loop over zeroed buffers to
extend relations. This bypasses the dedicated zero-extension interfaces,
leading to inconsistent code patterns. It also misses out on
platform-specific optimizations like posix_fallocate() or FileZero() that
mdzeroextend() leverages instead of relying on sparse-file hole semantics.

*The Fix*
The attached patch refactors these remaining instances to use
smgrzeroextend() (and mdzeroextend() directly in md.c):

1. bufmgr.c: Replaces memset() + smgrextend() with a single
smgrzeroextend() call to bulk-extend the destination relation.
2. bulk_write.c: Eliminates the file-scope zero_buffer and the while loop,
substituting a single smgrzeroextend() call to fill non-sequential write
gaps efficiently.
3. md.c: Removes the aligned palloc_aligned zero-buffer allocation in
_mdfd_getseg(), replacing it with a direct call to mdzeroextend() to pad
short segments.

This unifies all zero-fill relation extensions, improves code readability,
and ensures optimized zero-extension paths are used consistently across the
storage manager.

Reviewed by: Heikki Linnakangas

*The Broader Vision*
Beyond simple code cleanup, enforcing the responsibility separation of
smgrextend() and smgrzeroextend() opens up a clean way to address a
long-standing data validation challenge.
Today, PostgreSQL can generate all-zero pages during relation extension and
accept an all-zero page into the buffer cache as if it were valid. Because
the engine cannot distinguish whether an all-zero page was created
intentionally or corrupted by an external bug, corrupted pages can enter
the buffer cache undetected. For example, if a valid heap page is
overwritten with zeros, an index scan will not report an error and will
simply, silently return "tuple not found." Once that page is selected for
an insert or update, it gets re-initialized, cementing the silent data
corruption permanently into the WAL stream.
To close this gap, we want to completely eliminate all-zero pages from
regular relation extension so we can accurately detect when an all-zero
page is the result of a bug. While a Proof of Concept (POC) for this
broader change is still in progress, implementing this refactoring is an
important first step.

*Testing Performed*

- Regression Tests: Ran make check-world to ensure relation extension
and bootstrap/creation paths function exactly as expected.
- Compilation: Verified a clean build with no warnings on GCC and Clang.

Feedback and suggestions on both this patch and the upcoming vision are
highly welcome!

Best regards,
Peipei Yin

Attachments:

t253396_1
0001-Use-smgrzeroextend-for-zero-filled-relation-extensio.patchapplication/octet-stream; name=0001-Use-smgrzeroextend-for-zero-filled-relation-extensio.patchDownload+13-21
#2Bharath Rupireddy
bharath.rupireddyforpostgres@gmail.com
In reply to: Peipei YIN (#1)
Re: [PATCH] Refactor remaining zero-fill relation extensions to use smgrzeroextend()

Hi,

On Wed, Aug 12, 2026 at 6:31 PM Peipei YIN <yinpeipei0426@gmail.com> wrote:

Hi hackers,

While reviewing relation extension paths, I noticed three places that still manually perform zero-fill operations using smgrextend(), even though smgrzeroextend() (and its underlying mdzeroextend()) exists specifically for this purpose.

The Problem
Currently, RelationCopyStorageUsingBuffer(), smgr_bulk_flush(), and segment padding in _mdfd_getseg() manually construct or loop over zeroed buffers to extend relations. This bypasses the dedicated zero-extension interfaces, leading to inconsistent code patterns. It also misses out on platform-specific optimizations like posix_fallocate() or FileZero() that mdzeroextend() leverages instead of relying on sparse-file hole semantics.

The Fix
The attached patch refactors these remaining instances to use smgrzeroextend() (and mdzeroextend() directly in md.c):

bufmgr.c: Replaces memset() + smgrextend() with a single smgrzeroextend() call to bulk-extend the destination relation.
bulk_write.c: Eliminates the file-scope zero_buffer and the while loop, substituting a single smgrzeroextend() call to fill non-sequential write gaps efficiently.
md.c: Removes the aligned palloc_aligned zero-buffer allocation in _mdfd_getseg(), replacing it with a direct call to mdzeroextend() to pad short segments.

This unifies all zero-fill relation extensions, improves code readability, and ensures optimized zero-extension paths are used consistently across the storage manager.

Thanks for sending the patch.

I read through the code and commits (4d330a61bb, f94e9141a0b) around
smgrextend and smgrzeroextend and did some experimentation.

@@ -5405,9 +5404,8 @@ RelationCopyStorageUsingBuffer(RelFileLocator srclocator,
  * Bulk extend the destination relation of the same size as the source
  * relation before starting to copy block by block.
  */
- memset(buf.data, 0, BLCKSZ);
- smgrextend(smgropen(dstlocator, INVALID_PROC_NUMBER), forkNum, nblocks - 1,
-   buf.data, true);
+ smgrzeroextend(smgropen(dstlocator, INVALID_PROC_NUMBER), forkNum, 0,
+   nblocks, true);

In the CREATE DATABASE path, smgrextend writes just one block with
zeros (out of N relation blocks only the last one gets written zero),
so this is already optimized today (which is why with posix_fallocate
the patch shows no visible benefit here). However, with smgrzeroextend
and file_extend_method=write_zeros (IOW, on platforms where
posix_fallocate doesn't exist), this patch increases the disk writes
(2x) and slows the query (2x).

I did a quick benchmark of CREATE DATABASE with a source database of
7.3GB (pgbench scale 500) on an m5d.4xlarge Amazon EC2 instance with a
gp3 (network-attached) data volume. Disk writes were captured from
/proc/diskstats sectors-written for the data device. Config used was
wal_level=minimal, fsync=on, checkpoint_timeout=24h, and small
vm.dirty_bytes=64MB / vm.dirty_background_bytes=32MB so dirty pages
are flushed mid-copy once they cross the threshold, rather than the
zero pages being overwritten in cache first.

I ran each configuration 3 times. The numbers below are the average
(variance was under 1%).

code exec time (s) disk writes (GB)
HEAD 59.2 7.3
patched, posix_fallocate 59.2 7.3
patched, write_zeros 119.1 14.6

I didn't dive deep into the other paths bulk_write.c and md.c changed
in this patch, so I'm not sure if they could also hit this problem.

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com

#3shihao zhong
zhong950419@gmail.com
In reply to: Bharath Rupireddy (#2)
Re: [PATCH] Refactor remaining zero-fill relation extensions to use smgrzeroextend()

Hi Peipei, Bharath,

I do not think this patch can reach the goal it states.

The goal is to remove all-zero pages from relation extension, so that
an all-zero page means corruption. But smgrzeroextend() is the function
that creates all-zero pages. Sending more code through it cannot reduce
them, because FileZero gives you the same all-zero page that a sparse
hole gives you.

The main extension path also creates them on purpose.
ExtendBufferedRelShared() calls smgrzeroextend(), and the comment just
above it says we do not need a checksum for all-zero pages. A page is
all zeros until the access method calls PageInit(), and vacuum tests
PageIsNew() because of that. An all-zero page is a normal state, which
is why bufpage.c has to accept one. The gap you found is real, but
closing it means changing that lifecycle, not changing which function
writes the zeros.

On the three hunks themselves.

1. bufmgr.c zero fills N blocks that the copy loop overwrites right after.
That is the cost Bharath measured.

2. md.c has the same shape and can write a whole segment, 1 GB at the
default, where today it writes 8 kB.

3. bulk_write.c changes nothing today. Every caller leaves a gap of at
most one block, and at one block mdzeroextend() falls back to the same
single write the current loop already does. From cleanup perspective,
that change make sense.

If the goal is instead that extension should reserve space, so a later
write cannot fail when the disk is full, that is a stronger argument
than the commit message makes, and worth stating on its own.

Applies cleanly on 6e70bef24e4, and the suites pass here.

Thanks,
Shihao

#4Bharath Rupireddy
bharath.rupireddyforpostgres@gmail.com
In reply to: Bharath Rupireddy (#2)
Re: [PATCH] Refactor remaining zero-fill relation extensions to use smgrzeroextend()

Hi,

On Thu, Aug 13, 2026 at 1:50 PM Bharath Rupireddy
<bharath.rupireddyforpostgres@gmail.com> wrote:

In the CREATE DATABASE path, smgrextend writes just one block with
zeros (out of N relation blocks only the last one gets written zero),
so this is already optimized today (which is why with posix_fallocate
the patch shows no visible benefit here). However, with smgrzeroextend
and file_extend_method=write_zeros (IOW, on platforms where
posix_fallocate doesn't exist), this patch increases the disk writes
(2x) and slows the query (2x).

code exec time (s) disk writes (GB)
HEAD 59.2 7.3
patched, posix_fallocate 59.2 7.3
patched, write_zeros 119.1 14.6

I didn't dive deep into the other paths bulk_write.c and md.c changed
in this patch, so I'm not sure if they could also hit this problem.

I looked at the other two places. _mdfd_getseg() has the same
optimization as the CREATE DATABASE path (out of N blocks, only the
last one gets zeroed), so the patch has the same problem there.
smgr_bulk_flush() already writes all the gap pages with zeros, so
using smgrzeroextend() there looks good to me.

Using smgrzeroextend() for every zero-fill relation extension, as
mentioned upthread [1], is a good idea. How about we pass only the
last block to smgrzeroextend() and mdzeroextend() in those two places,
something like the attached? This also removes the regression.

code exec time (s) disk writes (GB)
HEAD 58.9 7.3
v1, posix_fallocate 58.9 7.3
v1, write_zeros 118.5 14.6
v2, posix_fallocate 58.9 7.3
v2, write_zeros 58.9 7.3

Barring objections, I will mark the CF entry as Ready for Committer.

[1]:

The Broader Vision
Beyond simple code cleanup, enforcing the responsibility separation of smgrextend() and smgrzeroextend() opens up a clean way to address a long-standing data validation challenge.

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com

Attachments:

t253396_4
v2-0001-Use-smgrzeroextend-in-a-few-more-places.patchapplication/octet-stream; name=v2-0001-Use-smgrzeroextend-in-a-few-more-places.patchDownload+12-21
#5shihao zhong
zhong950419@gmail.com
In reply to: Bharath Rupireddy (#4)
Re: [PATCH] Refactor remaining zero-fill relation extensions to use smgrzeroextend()

Hi,

I reviewed v2. It fixes both regressions I raised on v1. With one
block, mdzeroextend() takes the same FileZero() path as the old
mdextend() call, so nothing changes at runtime there.

One request. smgrzeroextend(..., nblocks - 1, 1, ...) looks like a bug
unless you know why, and changing it to (0, nblocks) brings the 2x
regression back. Please add a one line comment in bufmgr.c and md.c
saying only the last block is written on purpose.

Nit, the "don't set checksum" comment in bulk_write.c no longer
applies, since no page is passed.

Note that v2 does not move toward the zero page detection idea. The
blocks before the last one are still holes, which read as zeros and
never pass through smgrzeroextend(). Making them non-zero means writing
them, which is the 2x cost Bharath measured.

Thanks,
Shihao

#6Bharath Rupireddy
bharath.rupireddyforpostgres@gmail.com
In reply to: shihao zhong (#5)
Re: [PATCH] Refactor remaining zero-fill relation extensions to use smgrzeroextend()

Hi,

On Thu, Sep 24, 2026 at 10:07 PM shihao zhong <zhong950419@gmail.com> wrote:

I reviewed v2. It fixes both regressions I raised on v1. With one
block, mdzeroextend() takes the same FileZero() path as the old
mdextend() call, so nothing changes at runtime there.

Thanks for reviewing.

One request. smgrzeroextend(..., nblocks - 1, 1, ...) looks like a bug
unless you know why, and changing it to (0, nblocks) brings the 2x
regression back. Please add a one line comment in bufmgr.c and md.c
saying only the last block is written on purpose.

It can take a while to understand that part when first looking at it.
Still, I would prefer not to add the comment, since it would mostly
end up restating what the code already does, unless anyone thinks
otherwise.

Nit, the "don't set checksum" comment in bulk_write.c no longer
applies, since no page is passed.

Reworded it to match an existing comment around smgrzeroextend().

Note that v2 does not move toward the zero page detection idea. The
blocks before the last one are still holes, which read as zeros and
never pass through smgrzeroextend(). Making them non-zero means writing
them, which is the 2x cost Bharath measured.

Right, I don't think this patch was meant to solve that, though I may
be missing something. What it does is keep the responsibilities of
smgrextend() and smgrzeroextend() separate, as mentioned upthread, and
that alone is worth having IMHO. I think the zero page detection part
would need changes to the API itself. Peipei, appreciate any thoughts
on this.

I attached the v3 patch. Please have a look. I don't think this needs
to be back-patched, since it is not fixing a bug.

--
Bharath Rupireddy
Amazon Web Services: https://aws.amazon.com

Attachments:

t253396_6
v3-0001-Use-smgrzeroextend-in-a-few-more-places.patchapplication/x-patch; name=v3-0001-Use-smgrzeroextend-in-a-few-more-places.patchDownload+12-21
#7shihao zhong
zhong950419@gmail.com
In reply to: Bharath Rupireddy (#6)
Re: [PATCH] Refactor remaining zero-fill relation extensions to use smgrzeroextend()

Hi Bharath,

I won't push on the comment. v3 looks good to me as a refactor. My +1
is for the refactor only, not for the zero page detection idea.

Thanks,
Shihao