WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

Поиск
Список
Период
Сортировка
Искать

WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
Вложения:
Hi,

My collegue Konstantin Knizhnik pointed out that we fail to mark pages
with a non-standard page layout with page_std=false in
RelationCopyStorageUsingBuffer when we WAL-log them. This causes us to
interpret the registered buffer as a standard buffer, and omit the
hole in the page, which for FSM/VM pages covers the whole page.

The immediate effect of this bug is that replicas and primaries in a
physical replication system won't have the same data in their VM- and
FSM-forks until the first VACUUM on the new database has WAL-logged
these pages again. Whilst not actively harmful for the VM/FSM
subsystems, it's definitely suboptimal.
Secondary unwanted effects are that AMs that use the buffercache- but
which don't use or update the pageheader- also won't see the main data
logged in WAL, thus potentially losing user data in the physical
replication stream or with a system crash. I've not looked for any
such AMs and am unaware of any that would have this issue, but it's
better to fix this.


PFA a patch that fixes this issue, by assuming that all pages in the
source database utilize a non-standard page layout.

Kind regards,

Matthias van de Meent
Neon (https://neon.tech)

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Tom Lane <tgl@sss.pgh.pa.us>
Дата:
Matthias van de Meent  writes:
> PFA a patch that fixes this issue, by assuming that all pages in the
> source database utilize a non-standard page layout.

Surely that cure is worse than the disease?

			regards, tom lane


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
On Mon, 13 May 2024 at 16:13, Tom Lane  wrote:
>
> Matthias van de Meent  writes:
> > PFA a patch that fixes this issue, by assuming that all pages in the
> > source database utilize a non-standard page layout.
>
> Surely that cure is worse than the disease?

I don't know where we would get the information whether the selected
relation fork's pages are standard-compliant. We could base it off of
the fork number (that info is available locally) but that doesn't
guarantee much.
For VM and FSM-pages we know they're essentially never
standard-compliant (hence this thread), but for the main fork it is
anyone's guess once the user has installed an additional AM - which we
don't detect nor pass through to the offending
RelationCopyStorageUsingBuffer.

As for "worse", the default template database is still much smaller
than the working set of most databases. This will indeed regress the
workload a bit, but only by the fraction of holes in the page + all
FSM/VM data.
I think the additional WAL volume during CREATE DATABASE is worth it
when the alternative is losing that data with physical
replication/secondary instances. Note that this does not disable page
compression, it just stops the logging of holes in pages; holes which
generally are only a fraction of the whole database.

It's not inconceivable that this will significantly increase WAL
volume, but I think we should go for correctness rather than fastest
copy. If we went with fastest copy, we'd better just skip logging the
FSM and VM forks because we're already ignoring the data of the pages,
so why not ignore the pages themselves, too? I don't think that holds
water when we want to be crash-proof in CREATE DATABASE, with a full
data copy of the template database.

Kind regards,

Matthias van de Meent
Neon (https://neon.tech)


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Mon, May 13, 2024 at 10:53 AM Matthias van de Meent
 wrote:
> It's not inconceivable that this will significantly increase WAL
> volume, but I think we should go for correctness rather than fastest
> copy.

I don't think we can afford to just do this blindly for the sake of a
hypothetical non-core AM that uses nonstandard pages. There must be
lots of cases where the holes are large, and where the WAL volume
would be a multiple of what it is currently. That's a *big*
regression.

> If we went with fastest copy, we'd better just skip logging the
> FSM and VM forks because we're already ignoring the data of the pages,
> so why not ignore the pages themselves, too? I don't think that holds
> water when we want to be crash-proof in CREATE DATABASE, with a full
> data copy of the template database.

This seems like a red herring. Either assuming standard pages is a
good idea or it isn't, and either logging the FSM and VM forks is a
good idea or it isn't, but those are two separate questions.

-- 
Robert Haas
EDB: http://www.enterprisedb.com


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Akshat Jaimini <destrex271@gmail.com>
Дата:
Hi,

Quick question, are there any more revisions left to be done on this patch from the previous feedback?
Or should I continue with reviewing the current patch?

Regards,
Akshat Jaimini

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Álvaro Herrera <alvherre@kurilemu.de>
Дата:
On 2024-Dec-10, Michael Paquier wrote:

> One potential way to move forward would be to spread the knowledge of
> page_std when logging a new page higher in the callers, then allow
> dbcommands.c to be smarter about that?

Matthias, is this patch still under consideration?

-- 
Álvaro Herrera         PostgreSQL Developer  —  https://www.EnterpriseDB.com/
"Update: super-fast reaction on the Postgres bugs mailing list. The report
was acknowledged [...], and a fix is under discussion.
The wonders of open-source !"
             https://twitter.com/gunnarmorling/status/1596080409259003906


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Michael Paquier <michael@paquier.xyz>
Дата:
Вложения:
On Mon, Aug 24, 2026 at 01:04:44AM +0800, Rogers Wang wrote:
> What changed since the last discussion
> --------------------------------------
> The divergence was assessed back then as "not actively harmful". That
> no longer holds in v19: commit add323da40a added
> Assert(BufferIsDirty(vmbuffer)) to heap_xlog_prune_freeze(), which
> makes the divergence fatal on assert builds after a switchover:
> 
> 1. The promoted standby has a zeroed VM, so VACUUM FREEZE sets the
>    bits again, emitting PRUNE records with no FPI for the VM buffer.
> 2. The old primary, rejoined as standby, still has the bits set with
>    an older page LSN, so replay takes the redo branch - but
>    visibilitymap_set() is a no-op there (bits already set) and the
>    buffer stays clean.
> 3. Assert(BufferIsDirty(vmbuffer)) fires, and the node crash-loops on
>    that record.
> 
> And even without assertions, the new database on the standby silently
> loses all all-visible/all-frozen bits and all free space data of every
> copied relation.

Hmm.  This warrants an open item for v19, at least to be discussed.
Adding Melanie in CC as the committer of add323da40a.
--
Michael

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Matthias van de Meent <boekewurm+postgres@gmail.com>
Дата:
Вложения:
On Mon, 31 Aug 2026 at 17:46, Melanie Plageman
 wrote:
>
> On Mon, Aug 31, 2026 at 1:37 AM Michael Paquier  wrote:
> >
> > Hmm.  This warrants an open item for v19, at least to be discussed.
> > Adding Melanie in CC as the committer of add323da40a.
>
> This part

I think a message got cut off.

> As for whether we should log full page images of the VM and FSM in
> RelationCopyStorageUsingBuffer(), that kind of seems like the right
> direction to go, but that doesn't feel backpatchable to me. I
> understand this doesn't address Matthias' concern about certain AMs,
> but it seems like a good idea to have the VM and FSM up-to-date after
> promotion and FPIs of just those forks doesn't seem like an
> unacceptable increase in WAL volume. I don't know if doing this will
> have any side effects or causes bugs in other situations, though. I'd
> have to think more about it...

IIUC, CREATE DATABASE doesn't allow concurrent R/RW connections to the
template database, for neither WAL_LOG nor FILE_COPY.  In this case
there shouldn't be any issues with copying VM pages that aren't
already present in the file-copy approach. The only difference here
would be that VM/FSM pages now get a more recent LSN on their pages,
and I think this should be fine because I can't think of a mechanism
that checks for (the consistency of) VM/FSM page LSNs.


Kind regards,

Matthias van de Meent
Databricks (https://www.databricks.com)


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
On Fri, Sep 11, 2026 at 4:44 PM Melanie Plageman
 wrote:
>
> > In master, it probably makes sense to change back the signature of
> > visibilitymap_set() to report if it did actually set the bit(s) and
> > then use that to decide whether to set the page LSN. Unless we don't
> > think it is too late in 19 to change the visibilitymap_set() API. It
> > does mean all the other callers of visibilitymap_set() are going to
> > discard the return value, but maybe that's okay?
>
> Since we are putting out a beta 4, I feel fine about changing the
> visiblitymap_set() API back. Here is a patch that does that.

I've pushed a fix for this and marked the open item as resolved.

- Melanie


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
On Mon, Aug 31, 2026 at 12:08 PM Matthias van de Meent
 wrote:
>
> On Mon, 31 Aug 2026 at 17:46, Melanie Plageman
>  wrote:
>
> > As for whether we should log full page images of the VM and FSM in
> > RelationCopyStorageUsingBuffer(), that kind of seems like the right
> > direction to go, but that doesn't feel backpatchable to me. I
> > understand this doesn't address Matthias' concern about certain AMs,
> > but it seems like a good idea to have the VM and FSM up-to-date after
> > promotion and FPIs of just those forks doesn't seem like an
> > unacceptable increase in WAL volume. I don't know if doing this will
> > have any side effects or causes bugs in other situations, though. I'd
> > have to think more about it...
>
> IIUC, CREATE DATABASE doesn't allow concurrent R/RW connections to the
> template database, for neither WAL_LOG nor FILE_COPY.  In this case
> there shouldn't be any issues with copying VM pages that aren't
> already present in the file-copy approach. The only difference here
> would be that VM/FSM pages now get a more recent LSN on their pages,
> and I think this should be fine because I can't think of a mechanism
> that checks for (the consistency of) VM/FSM page LSNs.

I now think we have to do something. While exploring another adjacent
topic, I realized that tuple locking has a seemingly unsolvable
problem with this.

If you have a page set all-frozen in the VM and then do CREATE
DATABASE STRATEGY WAL_LOG, your new database will have that page set
all-frozen in the VM on the primary and set neither all-visible nor
all-frozen on the standby. When that standby is promoted, you now have
a primary with the page NOT set all-frozen and a standby with the page
set all-frozen. If you then lock the tuple on the primary, it will
emit a WAL record with no XLH_LOCK_ALL_FROZEN_CLEARED flag because the
primary did not need to clear all-frozen. The standby will update the
xmax but not clear the all-frozen bit in the VM. Now you have a heap
page with a live xmax that is set all-frozen in the VM.

Basically, if you have some all-frozen data and do CREATE DATABASE
STRATEGY WAL_LOG and then failover and then do a SELECT FOR UPDATE,
you'll have data corruption. That seems bad.

I don't see any reasonable way to fix this other than to prevent it
from happening. Because we are only clearing the all-frozen bit,
including a VM clearing operation in every lock record in which the
page is all-visible, means that as soon as a page is all-visible every
single time we lock it the WAL record will have to include the VM page
-- which is very expensive.

This should fix that particular way to get into this situation
if (use_wal)
    log_newpage_buffer(dstBuf, forkNum != VISIBILITYMAP_FORKNUM &&
forkNum != FSM_FORKNUM);

But if there are other ways to get into this situation, I'm not quite
sure what we could do. I asked an LLM to come up with scenarios and
outside of RelationCopyStorageUsingBuffer(). It couldn't identify
other specific scenarios that could put us in this bad state. It
mentioned some things with incremental backups from before ed62d26caca
or bad basebackup/crash recovery/PITR scenarios, but I'd need to do
more investigation. After a cursory investigation, the possibility for
those to create this scenario and not other problems seems pretty
remote. Fixing RelationCopyStorageUsingBuffer() seems required at this
point, though.

- Melanie


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
Вложения:
On Wed, Sep 16, 2026 at 10:26 AM Melanie Plageman
 wrote:
>
> I now think we have to do something. While exploring another adjacent
> topic, I realized that tuple locking has a seemingly unsolvable
> problem with this.
>
> If you have a page set all-frozen in the VM and then do CREATE
> DATABASE STRATEGY WAL_LOG, your new database will have that page set
> all-frozen in the VM on the primary and set neither all-visible nor
> all-frozen on the standby. When that standby is promoted, you now have
> a primary with the page NOT set all-frozen and a standby with the page
> set all-frozen. If you then lock the tuple on the primary, it will
> emit a WAL record with no XLH_LOCK_ALL_FROZEN_CLEARED flag because the
> primary did not need to clear all-frozen. The standby will update the
> xmax but not clear the all-frozen bit in the VM. Now you have a heap
> page with a live xmax that is set all-frozen in the VM.
>
> Basically, if you have some all-frozen data and do CREATE DATABASE
> STRATEGY WAL_LOG and then failover and then do a SELECT FOR UPDATE,
> you'll have data corruption. That seems bad.

I attached an LLM-generated reproducer.

- Melanie

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Mon, Aug 31, 2026 at 11:47 AM Melanie Plageman
 wrote:
> As for whether we should log full page images of the VM and FSM in
> RelationCopyStorageUsingBuffer(), that kind of seems like the right
> direction to go, but that doesn't feel backpatchable to me. I
> understand this doesn't address Matthias' concern about certain AMs,
> but it seems like a good idea to have the VM and FSM up-to-date after
> promotion and FPIs of just those forks doesn't seem like an
> unacceptable increase in WAL volume. I don't know if doing this will
> have any side effects or causes bugs in other situations, though. I'd
> have to think more about it...

I feel like treating the VM and FSM as non-standard pages is the right
thing to do, because in fact they are not standard pages. Unless you
know something I don't, I think we need to fix
RelationCopyStorageUsingBuffer to treat them that way. What's your
reason for not wanting to back-patch that change?

AFAICS, the tougher question is what to do about the main fork. I
originally resisted the idea of treating all pages as non-standard
pages here because, well, most of the time they will be standard, and
treating them as non-standard adds considerable expense. However, a
bit of exploration with Claude poked a few holes in this idea. It
notes that:

1. RelationCopyStorage treats all pages as non-standard, so having
RelationCopyStorageUsingBuffer do otherwise is inconsistent.

2. ginDeletePostingPage has a comment saying that GIN uses
non-standard pages prior to 9.4.

3. The value of STRATEGY WAL_LOG is that it's faster for small
databases, so the additional WAL volume may not be a huge deal anyway.

So I'm starting to think Matthias had the right idea back in 2024. It
still seems like a lamentable change to me, but to quote Tom quoting
an unnamed wise man: "I can make this code arbitrarily fast, if it
doesn't have to give the right answer." As far as that goes, point #2
is the strongest argument: there aren't likely many people who have a
GIN index that hasn't been rewritten since pre-9.4 and who have that
index inside of a database that they use as a template, but any such
people who do exist will be justifiably annoyed if CREATE DATABASE
with any set of options produces a corrupt copy.

-- 
Robert Haas


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
On Wed, Sep 16, 2026 at 5:59 PM Robert Haas  wrote:
>
> On Mon, Aug 31, 2026 at 11:47 AM Melanie Plageman
>  wrote:
> > As for whether we should log full page images of the VM and FSM in
> > RelationCopyStorageUsingBuffer(), that kind of seems like the right
> > direction to go, but that doesn't feel backpatchable to me. I
> > understand this doesn't address Matthias' concern about certain AMs,
> > but it seems like a good idea to have the VM and FSM up-to-date after
> > promotion and FPIs of just those forks doesn't seem like an
> > unacceptable increase in WAL volume. I don't know if doing this will
> > have any side effects or causes bugs in other situations, though. I'd
> > have to think more about it...
>
> I feel like treating the VM and FSM as non-standard pages is the right
> thing to do, because in fact they are not standard pages. Unless you
> know something I don't, I think we need to fix
> RelationCopyStorageUsingBuffer to treat them that way. What's your
> reason for not wanting to back-patch that change?

That was before I realized that it allows us to trivially cause a
serious data corruption bug with tuple locking. We should definitely
backpatch the part that passes false for VM and FSM.

> AFAICS, the tougher question is what to do about the main fork. I
> originally resisted the idea of treating all pages as non-standard
> pages here because, well, most of the time they will be standard, and
> treating them as non-standard adds considerable expense. However, a
> bit of exploration with Claude poked a few holes in this idea. It
> notes that:
>
> 1. RelationCopyStorage treats all pages as non-standard, so having
> RelationCopyStorageUsingBuffer do otherwise is inconsistent.
>
> 2. ginDeletePostingPage has a comment saying that GIN uses
> non-standard pages prior to 9.4.
>
> 3. The value of STRATEGY WAL_LOG is that it's faster for small
> databases, so the additional WAL volume may not be a huge deal anyway.

Andres suggested off-list having CreateDatabaseUsingWalLog() thread
information from the catalog about whether the page is a normal heap
page down into RelationCopyStorageUsingBuffer().

I looked into it and we could, when scanning source database pg_class
(ScanSourceDatabasePgClassTuple()), check something like:
RELKIND_HAS_TABLE_AM(classForm->relkind) && classForm->relam ==
HEAP_TABLE_AM_OID
and allowing the "hole punching" if so.

And, it's even easier to do this in RelationCopyStorage() without any
extra catalog info because the callers know what type of relation it
is. So, we could fix RelationCopyStorageUsingBuffer() and make it
consistent with RelationCopyStorage() at the same time (master only).

- Melanie


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
Вложения:
On Tue, Sep 22, 2026 at 7:12 PM Melanie Plageman
 wrote:
>
> Andres suggested off-list having CreateDatabaseUsingWalLog() thread
> information from the catalog about whether the page is a normal heap
> page down into RelationCopyStorageUsingBuffer().

Upon further off-list discussion, instead of checking the AM, we can
just check if the space between pd_upper and pd_lower is all zeroes.
If it is, there is no harm in omitting it. It should always work,
allows the optimization in more cases, and requires less code.
Attached patch does that.

I also added a test. It compares the pages of all forks of a table
between a primary and standby after doing CREATE DATABASE USING
STRATEGY WAL_LOG. I compare the whole page byte-by-byte including page
header and LSN. Are those always guaranteed to be the same on the
standby as well?

- Melanie

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Melanie,

Thanks for the patch. I applied it on master (6b3f8857aa8). It applies and builds cleanly.


Upon further off-list discussion, instead of checking the AM, we can
just check if the space between pd_upper and pd_lower is all zeroes.
If it is, there is no harm in omitting it. It should always work,
allows the optimization in more cases, and requires less code.
Attached patch does that.

I also added a test. It compares the pages of all forks of a table
between a primary and standby after doing CREATE DATABASE USING
STRATEGY WAL_LOG. I compare the whole page byte-by-byte including page
header and LSN. Are those always guaranteed to be the same on the
standby as well?


The approach looks correct to me. On replay, RestoreBlockImage() fills the hole with zeros, so leaving out a hole that is already all zeros
can't change the page. Because RelationCopyStorageUsingBuffer() and XLogRecordAssemble() now share PageFreeSpaceBoundsAreValid(), the range
checked for zeros is exactly the range that gets omitted. I like that it needs no AM or fork knowledge.

On your question about the page header, I don't think the whole page is guaranteed to match.
pd_lsn should match. log_newpage() sets it on the primary, and XLogReadBufferForRedoExtended() sets it to the same record LSN after restoring the image.

pd_checksum doesn't, though. The image is taken right after the memcpy, so it carries the template page's checksum. After that, each node's
in-memory pd_checksum depends on whether that node has flushed the page (which, since 41d3d64e87a, updates the checksum in place) or re-read it
from disk. The test checkpoints and restarts the primary, but does nothing comparable on the standby.

I ran some experiments with a streaming standby (checksums on), page 0 of the copied table's vm fork looked like this:

                                  lsn         checksum
    primary, after CHECKPOINT     0/3082BA50    -24598
    standby, just replayed        0/3082BA50     -7694   (= template's)
    standby, after CHECKPOINT     0/3082BA50    -24598

The fsm page behaves the same way. After the standby's CHECKPOINT the raw pages matched exactly.

The test passes as written, but I think only because allows_streaming sets shared_buffers = 1MB, so the standby evicts (and re-checksums) the copied pages before the comparison.
Adding $standby->append_conf('postgresql.conf', 'shared_buffers = 128MB');
before $standby->start makes both the vm and fsm checks fail here. 
The only differing bytes are 8-9 (pd_checksum); pd_lsn matches. A CHECKPOINT on the standby before comparing, or comparing from SizeOfPageHeaderData onward, should make it robust.

A few things about the test:
1. The loop compares only block 0 of the vm and fsm forks. Your mail mentions comparing all forks, but the main fork isn't checked.
If that was left out on purpose (hint bits, say), a comment explaining why would help. Comparing every block of each fork would also make
the test more robust. The FSM is multi-level, and the old bug affected all of its pages.

2. In the unpatched build, every vm and fsm image the copy wrote had "hole: offset: 24, length: 8168", i.e. only the page header was
logged. So a vm/fsm check on any non-empty block will catch a regression.

Regarding WAL volume, in my test, after deletes and VACUUM, almost no heap or btree page had an all-zero hole. Pruning and compaction leave the old
tuple bytes behind. So for templates with any update/delete history, most main-fork pages are now logged in full. I measured WAL from
CREATE DATABASE ... STRATEGY WAL_LOG with and without the bufmgr.c changes.
The two test templates each had a 1M-row table with a btree index:

    template                                     unpatched   patched
    template1 (stock)                               4.5 MB    6.0 MB
    INSERT 1M rows; VACUUM FREEZE                   113 MB    114 MB
    same, then DELETE 1/3, UPDATE 10%, VACUUM        79 MB    117 MB

In the delete/update case, pg_waldump --bkp-details showed all 11364 heap pages and 2735 of 2745 btree pages logged as full images, compared with
almost none before. When VACUUM prunes a page, it compacts the remaining tuples but doesn't zero the space it frees, so the hole still
holds old tuple data and fails the all-zeros check. Btree pages behave the same way once VACUUM removes index entries. Even stock template1 loses the hole on 125 catalog pages, presumably because initdb updates and deletes catalog rows.

I think correctness has to come first, and the append-only case costs almost nothing extra. But for a template whose tables have had deletes
or updates followed by VACUUM, CREATE DATABASE wrote about 50% more WAL in my test (79 MB vs 117 MB), so it might be worth mentioning in the commit message. Do you think it's worth keeping hole punching for pages we know are standard (e.g. heap and btree), or is the simpler rule the better trade-off?

Regarding back-patching, pg_memory_is_all_zeros() was added in v18 (commit 07e9e28b56d), so v15-v17 will need it back-patched or an open-coded
loop. The XLogRecordAssemble() refactor isn't needed for the fix and could stay master-only, if you'd prefer the back branches to change as
little as possible.

Regards,
Surya Poondla

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Mon, Oct 12, 2026 at 4:07 PM Melanie Plageman
 wrote:
> Upon further off-list discussion, instead of checking the AM, we can
> just check if the space between pd_upper and pd_lower is all zeroes.
> If it is, there is no harm in omitting it. It should always work,
> allows the optimization in more cases, and requires less code.
> Attached patch does that.

The problem with this approach is that it also includes the hole data
when the page is standard but the space between pd_upper and pd_lower
contains leftover garbage rather than zero bytes. That case is common:
when we prune-and-defragment heap pages, we don't zero the hole. I
think it would be worth trying to pass down the AM OID and always use
page_std = true for main-fork heap and btree pages (and maybe other
in-core AMs with no known legacy problems). That would mitigate the
practical downsides of the patch considerably. Whether you do that or
not, it's probably worth mentioning the performance concern in the
commit message. With that change, the downside would only exist for
out-of-core AMs, which do exist, and they could consider vigorous
hole-zeroing as a workaround.

-- 
Robert Haas
Databricks


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
Вложения:
On Fri, Nov 6, 2026 at 10:13 AM Robert Haas  wrote:
>
> On Mon, Oct 12, 2026 at 4:07 PM Melanie Plageman
>  wrote:
> > Upon further off-list discussion, instead of checking the AM, we can
> > just check if the space between pd_upper and pd_lower is all zeroes.
> > If it is, there is no harm in omitting it. It should always work,
> > allows the optimization in more cases, and requires less code.
> > Attached patch does that.
>
> The problem with this approach is that it also includes the hole data
> when the page is standard but the space between pd_upper and pd_lower
> contains leftover garbage rather than zero bytes. That case is common:
> when we prune-and-defragment heap pages, we don't zero the hole. I
> think it would be worth trying to pass down the AM OID and always use
> page_std = true for main-fork heap and btree pages (and maybe other
> in-core AMs with no known legacy problems). That would mitigate the
> practical downsides of the patch considerably. Whether you do that or
> not, it's probably worth mentioning the performance concern in the
> commit message. With that change, the downside would only exist for
> out-of-core AMs, which do exist, and they could consider vigorous
> hole-zeroing as a workaround.

I was aware that prune/defrag doesn't zero the data and so that would
not be included. I was mostly concerned that singling out heap tables
and btree felt a little inexact. But I suppose since it's a pretty
trivial diff to thread that information up from
ScanSourceDatabasePgClassTuple() to RelationCopyStorageUsingBuffer(),
it's worth doing.

Attached v2 uses a hybrid approach that passes page_std for heap
tables and btree indexes as well as when the data between pd_upper and
pd_lower is all zeroes. That allows other AMs to zero out that area if
they want to preserve the old behavior and avoid a regression (which I
think was what you were suggesting).

I also updated the test to use pg_visibilitymap_summary() instead of
comparing the raw page, which should fix test stability concerns.

The second commit in the patch set is targeting master only and would
extend this approach to RelationCopyStorage(), which would reduce the
WAL volume produced and works even more naturally there because they
already know the relation AM and page layout.

- Melanie

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
Thanks for the review and analysis.

On Tue, Oct 13, 2026 at 8:39 PM surya poondla  wrote:
>
>> I also added a test. It compares the pages of all forks of a table
>> between a primary and standby after doing CREATE DATABASE USING
>> STRATEGY WAL_LOG. I compare the whole page byte-by-byte including page
>> header and LSN. Are those always guaranteed to be the same on the
>> standby as well?
>
> The approach looks correct to me. On replay, RestoreBlockImage() fills the hole with zeros, so leaving out a hole that is already all zeros
> can't change the page. Because RelationCopyStorageUsingBuffer() and XLogRecordAssemble() now share PageFreeSpaceBoundsAreValid(), the range
> checked for zeros is exactly the range that gets omitted. I like that it needs no AM or fork knowledge.
>
> On your question about the page header, I don't think the whole page is guaranteed to match.
> pd_lsn should match. log_newpage() sets it on the primary, and XLogReadBufferForRedoExtended() sets it to the same record LSN after restoring the image.
>
> pd_checksum doesn't, though. The image is taken right after the memcpy, so it carries the template page's checksum. After that, each node's
> in-memory pd_checksum depends on whether that node has flushed the page (which, since 41d3d64e87a, updates the checksum in place) or re-read it
> from disk. The test checkpoints and restarts the primary, but does nothing comparable on the standby.

Thanks for the feedback and for doing that investigation. I changed
the test to just check the VM contents across primary and standby with
pg_visibilitymap_summary(). That should resolve this issue.

> A few things about the test:
> 1. The loop compares only block 0 of the vm and fsm forks. Your mail mentions comparing all forks, but the main fork isn't checked.
> If that was left out on purpose (hint bits, say), a comment explaining why would help. Comparing every block of each fork would also make
> the test more robust. The FSM is multi-level, and the old bug affected all of its pages.

In the new version of the test, I only check the VM page contents are
the same on primary and standby. I'm not too worried about checking
the FSM because it is never a correctness issue for the FSM to be
wrong. We could add something to the test checking that the contents
of the main fork are the same on primary and standby, but that
wouldn't fail without the commit (since it wasn't broken before), so I
didn't do that so far.

> 2. In the unpatched build, every vm and fsm image the copy wrote had "hole: offset: 24, length: 8168", i.e. only the page header was
> logged. So a vm/fsm check on any non-empty block will catch a regression.

Right. The new test only compares the VM, so it is only examining one
page. So, that should be efficient enough.

> Regarding WAL volume, in my test, after deletes and VACUUM, almost no heap or btree page had an all-zero hole. Pruning and compaction leave the old
> tuple bytes behind. So for templates with any update/delete history, most main-fork pages are now logged in full.
<-- snip -->
> I think correctness has to come first, and the append-only case costs almost nothing extra. But for a template whose tables have had deletes
> or updates followed by VACUUM, CREATE DATABASE wrote about 50% more WAL in my test (79 MB vs 117 MB), so it might be worth mentioning in the commit message. Do you think it's worth keeping hole punching for pages we know are standard (e.g. heap and btree), or is the simpler rule the better trade-off?

After trying to implement it, excepting heap tables and btree indexes
was a relatively small diff, so I went ahead and did that in v2.

> Regarding back-patching, pg_memory_is_all_zeros() was added in v18 (commit 07e9e28b56d), so v15-v17 will need it back-patched or an open-coded
> loop.

Good point. I haven't tried yet, but I think it shouldn't be too hard
to do this ourselves in backbranches. I will check.

> The XLogRecordAssemble() refactor isn't needed for the fix and could stay master-only, if you'd prefer the back branches to change as
> little as possible.

I think it's probably best to ensure that their criteria are the same,
ensuring that the bytes proven safe to discard are exactly those
removed from the full-page image. It's less of a code cleanup and more
of a code drift protection. But I might be able to be convinced
otherwise.

- Melanie


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Melanie, 
Thanks for the feedback and for doing that investigation. I changed
the test to just check the VM contents across primary and standby with
pg_visibilitymap_summary(). 

Thanks for v2 and for addressing all the points. Both patches apply cleanly on master (8d87367b39e) and build without warnings. 

I reran the same WAL measurements as before, with CREATE DATABASE ... STRATEGY WAL_LOG on master vs v2 (the two test templates each have a
1M-row table with a btree index):

    template                                                           master       v2
    template1 (stock)                                                 4549 kB   5733 kB
    1M rows inserted, VACUUM FREEZE                 113 MB    114 MB
    same, after deleting 1/3 and updating 10%,
      then VACUUM                                                    79 MB     80 MB

With v1 the last case was 117 MB, so the regression is gone. The remaining increase, mostly visible for template1, is the VM and FSM pages now being logged in full, which is the fix itself.

For 0002, ALTER TABLE/INDEX ... SET TABLESPACE on the delete/update
  table:

                        master       v2
    heap              89 MB     61 MB
    btree index    22 MB     13 MB

The test passes fine on v2 and for master it fails as expected on "copied table visibility map matches standby".
The standby shows f|f for all 45 blocks, where the primary shows t|t. It
compares per-block pg_visibility_map() output, which also covers the check-every-block point from before.

A minor optional suggestion, isnt($primary_visibility_map, '', ...) only checks that rows come back. If VACUUM (FREEZE) ever left the bits
unset, both nodes would show f|f and the test would pass without testing anything. Checking that the primary has at least one
all-frozen page would guard against that.

Overall v2 looks good to me.

Regards,
Surya Poondla

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Hi,

On Wed, Nov11, 2026 at 06:10 AM Melanie Plageman wrote:
>
> Attached v2 uses a hybrid approach that passes page_std for heap
> tables and btree indexes as well as when the data between pd_upper and
> pd_lower is all zeroes. That allows other AMs to zero out that area if
> they want to preserve the old behavior and avoid a regression (which I
> think was what you were suggesting).
While analyzing an issue related to the visibility map, I reviewed the 
0001 patch a bit. The fix looks good to me.

I just have one minor comment on the TAP test in 0001. IIUC, the 
pre-existing test in 034_create_database.pl was added by commit 
8a8661828ae to verify that when CREATE DATABASE loads the template's 
pg_class into shared_buffers, it marks those buffers as permanent so 
that a subsequent checkpoint flushes them to disk.

But with 0001, the modified test vacuuming tab_db_before_create_1 in 
template1 beforehand loads template1's pg_class into shared_buffers with 
BM_PERMANENT already set before CREATE DATABASE runs. If we want to keep 
the original regression coverage, maybe we could run the new test steps 
after the pre-existing test.

-- 
Best Regards,
Zhijie Hou


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
Вложения:
On Sat, Nov 14, 2026 at 8:08 AM Zhijie Hou  wrote:
>
> I just have one minor comment on the TAP test in 0001. IIUC, the
> pre-existing test in 034_create_database.pl was added by commit
> 8a8661828ae to verify that when CREATE DATABASE loads the template's
> pg_class into shared_buffers, it marks those buffers as permanent so
> that a subsequent checkpoint flushes them to disk.
>
> But with 0001, the modified test vacuuming tab_db_before_create_1 in
> template1 beforehand loads template1's pg_class into shared_buffers with
> BM_PERMANENT already set before CREATE DATABASE runs. If we want to keep
> the original regression coverage, maybe we could run the new test steps
> after the pre-existing test.

Ah, thanks so much for catching this. I read the test and not the
commit message adding it and thought it was just trying to make sure
that tables added after the copy didn't end up in the copied database
-- which, if I think about it, would have been a silly test. I've
changed it in attached v3 to retain the coverage in the initial test.

I also realized while editing this that I'll have to make a wrapper
version of CreateAndCopyRelationData() for the backports since it is
public. A bit annoying but I think better than the alternatives.

- Melanie

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
On Wed, Nov 11, 2026 at 6:14 PM surya poondla  wrote:
>
> A minor optional suggestion, isnt($primary_visibility_map, '', ...) only checks that rows come back. If VACUUM (FREEZE) ever left the bits
> unset, both nodes would show f|f and the test would pass without testing anything. Checking that the primary has at least one
> all-frozen page would guard against that.

Okay, I did this in v3.

- Melanie


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
surya poondla <suryapoondla4@gmail.com>
Дата:

Hi Melanie,

Thanks for v3 and for adding the all-frozen check.

v3 looks good.
 
A few small comments:
1. In 0002, tablecmds.c already includes catalog/pg_am.h, which exports
catalog/pg_am_d.h, so the added #include "catalog/pg_am_d.h" is redundant.

2. For the back-branch wrapper of CreateAndCopyRelationData(), I'd
suggest it pass false for the main fork. For an unknown caller that is always correct, the all-zeroes check still keeps the saving
whenever the hole is actually zero, and the non-main forks are handled correctly either way.

Regards,
Surya Poondla

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Вложения:
Hi,

On Tue, Nov17, 2026 at 01:35 AM Melanie Plageman wrote:
> On Sat, Nov 14, 2026 at 8:08 AM Zhijie Hou  wrote:
> >
> > I just have one minor comment on the TAP test in 0001. IIUC, the
> > pre-existing test in 034_create_database.pl was added by commit
> > 8a8661828ae to verify that when CREATE DATABASE loads the template's
> > pg_class into shared_buffers, it marks those buffers as permanent so
> > that a subsequent checkpoint flushes them to disk.
> >
> > But with 0001, the modified test vacuuming tab_db_before_create_1 in
> > template1 beforehand loads template1's pg_class into shared_buffers
> > with BM_PERMANENT already set before CREATE DATABASE runs. If we
> > want to keep the original regression coverage, maybe we could run
> > the new test steps after the pre-existing test.
>
> Ah, thanks so much for catching this. I read the test and not the
> commit message adding it and thought it was just trying to make sure
> that tables added after the copy didn't end up in the copied database
> -- which, if I think about it, would have been a silly test. I've
> changed it in attached v3 to retain the coverage in the initial test.
>
> I also realized while editing this that I'll have to make a wrapper
> version of CreateAndCopyRelationData() for the backports since it is
> public. A bit annoying but I think better than the alternatives.
Thanks for updating the patch.

I think we also need to increase shared_buffers (e.g., to 16MB), because 
$node->init(allows_streaming => 1) sets shared_buffers to 1MB 
internally, causing the pg_class pages to be evicted from shared_buffers 
before CREATE TABLE runs, so the test could not reach the old bug path.

BTW, while looking into why the wal_consistency_checking test didn't 
catch this bug, I noticed that verifyBackupPageConsistency() also masks 
out all the bits in VM pages via heap_mask() (somewhat similar to this 
bug, since it treats pd_lower..pd_upper as unused space), so the 
consistency check for VM pages always "passes".  Once we avoid masking 
the VM bitmap there (see the attached draft patch for reference), the 
existing test catches this CREATE DB WAL_LOG bug right away:

   PG_TEST_EXTRA=wal_consistency_checking meson test -C build 
recovery/027_stream_regress

So if it's worth increasing the possibility of catching similar VM bugs, 
maybe we could improve that as well (in a separate patch or thread).

-- 
Best Regards,
Zhijie Hou

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
On Tue, Nov 17, 2026 at 10:21 AM Zhijie Hou  wrote:
>
> I think we also need to increase shared_buffers (e.g., to 16MB), because
> $node->init(allows_streaming => 1) sets shared_buffers to 1MB
> internally, causing the pg_class pages to be evicted from shared_buffers
> before CREATE TABLE runs, so the test could not reach the old bug path.

Ah, okay. I'll do that. The original test feels awfully fragile. Is
there something we could do to strengthen it? Like check that one of
the buffers is marked BM_PERMANENT somehow? It seems very trivial to
accidentally eliminate the coverage. And there are of course lots of
ways for those buffers to get evicted.

> BTW, while looking into why the wal_consistency_checking test didn't
> catch this bug, I noticed that verifyBackupPageConsistency() also masks
> out all the bits in VM pages via heap_mask() (somewhat similar to this
> bug, since it treats pd_lower..pd_upper as unused space), so the
> consistency check for VM pages always "passes".  Once we avoid masking
> the VM bitmap there (see the attached draft patch for reference), the
> existing test catches this CREATE DB WAL_LOG bug right away:
>
>    PG_TEST_EXTRA=wal_consistency_checking meson test -C build
> recovery/027_stream_regress
>
> So if it's worth increasing the possibility of catching similar VM bugs,
> maybe we could improve that as well (in a separate patch or thread).

Ha, I didn't realize that wal_consistency_checking wasn't validating
the VM pages at all basically. I have a patch in this thread [1] to
stop masking PD_ALL_VISIBLE on heap pages, which I planned to commit
along with some other VM hardening in the next few weeks. Seems like I
should also do something about masking the whole VM pages themselves
too.

- Melanie

[1] https://www.postgresql.org/message-id/CAAKRu_aRdQ6RjneKeQh9%2BRVMFgMrtjTYFX%3DzDgBdSiQ8JDs6Jg%40mail.gmail.com


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
surya poondla <suryapoondla4@gmail.com>
Дата:
Hi Zhijie,

Nice find on the verifyBackupPageConsistency(). I tried your draft patch with a primary and a streaming
standby, both with wal_consistency_checking = 'heap,heap2'. 

With your patch on master, the standby stops after a plain CREATE DATABASE from template1, on a catalog insert (from CREATE EXTENSION) in the new database:

    FATAL:  inconsistent page found, rel 1663/16384/2608, forknum 2, blkno 0

With v3 applied as well, the same workload runs clean.

The fix looks good to me. One small comment, special-casing VISIBILITYMAP_FORKNUM in verifyBackupPageConsistency() makes sense to
avoid changing rm_mask(). On master it might be cleaner to pass the fork number to rm_mask and let heap_mask() skip mask_unused_space() for VM
pages, keeping your approach for the back branches.

Separately, since VM pages are now actually compared, any VM change that bypasses WAL will show up as an inconsistency.
heap_page_fix_vm_corruption() in pruneheap.c clears corrupted VM bits without WAL ("This VM clear is not WAL-logged ..."), would it make sense to WAL-log that clear?
Today the repair only fixes the primary, a standby keeps the corrupted bit, so its index-only scans can still trust it, and it comes back after a failover.
WAL-Logging it would fix the standby too and keep the new check from tripping over it. That's probably a separate patch, though.

Regards,
Surya Poondla

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Zhijie Hou <houzhijie22@gmail.com>
Дата:
Hi,

On Wed, Nov18, 2026 at 06:47 AM Melanie Plageman wrote:
> On Tue, Nov 17, 2026 at 10:21 AM Zhijie Hou  wrote:
> >
> > I think we also need to increase shared_buffers (e.g., to 16MB),
> > because $node->init(allows_streaming => 1) sets shared_buffers to
> > 1MB internally, causing the pg_class pages to be evicted from
> > shared_buffers before CREATE TABLE runs, so the test could not reach
> > the old bug path.
>
> Ah, okay. I'll do that. The original test feels awfully fragile. Is
> there something we could do to strengthen it? Like check that one of
> the buffers is marked BM_PERMANENT somehow? It seems very trivial to
> accidentally eliminate the coverage. And there are of course lots of
> ways for those buffers to get evicted.
Maybe we could add a few comments above the CREATE DATABASE command to 
give developers a hint, and if it's worth it, we could add a check after 
the command to verify that pg_class's pages stay in the buffer cache 
(But note that if we add this check, we'd better disable autovaccum to 
prevent background access):

# Verify that scanning template1's pg_class performs zero disk reads,
# confirming its pages were not evicted by CREATE DATABASE.
is( $node->safe_psql(
		$db_template, q{
	SELECT pg_stat_get_xact_blocks_fetched('pg_class'::regclass) -
	       pg_stat_get_xact_blocks_hit('pg_class'::regclass)
	FROM pg_class
	HAVING sum(relpages) >= 0;
}),
	"0",
	"template pg_class pages remain cached after CREATE DATABASE");

-- 
Best Regards,
Zhijie Hou


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
Вложения:
On Wed, Nov 18, 2026 at 10:42 AM Zhijie Hou  wrote:
>
> On Wed, Nov18, 2026 at 06:47 AM Melanie Plageman wrote:
>
> > Ah, okay. I'll do that. The original test feels awfully fragile. Is
> > there something we could do to strengthen it? Like check that one of
> > the buffers is marked BM_PERMANENT somehow? It seems very trivial to
> > accidentally eliminate the coverage. And there are of course lots of
> > ways for those buffers to get evicted.
>
> Maybe we could add a few comments above the CREATE DATABASE command to
> give developers a hint, and if it's worth it, we could add a check after
> the command to verify that pg_class's pages stay in the buffer cache
> (But note that if we add this check, we'd better disable autovaccum to
> prevent background access):
>
> # Verify that scanning template1's pg_class performs zero disk reads,
> # confirming its pages were not evicted by CREATE DATABASE.
> is( $node->safe_psql(
>                 $db_template, q{
>         SELECT pg_stat_get_xact_blocks_fetched('pg_class'::regclass) -
>                pg_stat_get_xact_blocks_hit('pg_class'::regclass)
>         FROM pg_class
>         HAVING sum(relpages) >= 0;
> }),
>         "0",
>         "template pg_class pages remain cached after CREATE DATABASE");

I decided to just add a comment to the test instead. I've now
committed and backpatched the main fix. The remaining patch attached
is targeted at master only and applies the optimization to
RelationCopyStorage(). I've added a few things since the last version
including a test.

- Melanie

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Michael Paquier <michael@paquier.xyz>
Дата:
Вложения:
On Tue, Nov 17, 2026 at 11:20:54PM +0800, Zhijie Hou wrote:
> I think we also need to increase shared_buffers (e.g., to 16MB), because
> $node->init(allows_streaming => 1) sets shared_buffers to 1MB internally,
> causing the pg_class pages to be evicted from shared_buffers before CREATE
> TABLE runs, so the test could not reach the old bug path.

If we care about this level of tuning, I'd suspect that just bumping
shared_buffers if the wal_consistency_checking switch is enabled
would be fine to do instead of having a buildfarm member that uses a
custom configuration file.  wal_consistency_checking consumes a lot of
resources, so this would not hurt more.  Your ideas around lifting
some of the masking of the VM pages would make that more valuable in
the long run, as least it seems so to me.
--
Michael

Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
On Thu, Nov 19, 2026 at 7:01 PM Michael Paquier  wrote:
>
> On Tue, Nov 17, 2026 at 11:20:54PM +0800, Zhijie Hou wrote:
> > I think we also need to increase shared_buffers (e.g., to 16MB), because
> > $node->init(allows_streaming => 1) sets shared_buffers to 1MB internally,
> > causing the pg_class pages to be evicted from shared_buffers before CREATE
> > TABLE runs, so the test could not reach the old bug path.
>
> If we care about this level of tuning, I'd suspect that just bumping
> shared_buffers if the wal_consistency_checking switch is enabled
> would be fine to do instead of having a buildfarm member that uses a
> custom configuration file.  wal_consistency_checking consumes a lot of
> resources, so this would not hurt more.  Your ideas around lifting
> some of the masking of the VM pages would make that more valuable in
> the long run, as least it seems so to me.

We actually needed the increased shared_buffers to preserve the
regression coverage of the original test unrelated to
wal_consistency_checking.

- Melanie


Re: WAL_LOG CREATE DATABASE strategy broken for non-standard page layouts

От:
Melanie Plageman <melanieplageman@gmail.com>
Дата:
On Thu, Nov 19, 2026 at 4:42 PM Melanie Plageman
 wrote:
>
> I've now
> committed and backpatched the main fix. The remaining patch attached
> is targeted at master only and applies the optimization to
> RelationCopyStorage(). I've added a few things since the last version
> including a test.

I've also committed this (RelationCopyStorage() optimization) to
master and started a new thread about wal_consistency_checking [1].

- Melanie

[1] https://www.postgresql.org/message-id/CAAKRu_bozJHE=Za4o1yZaPmW_rjG5DrUSDfEjOZkjvmaeN+EEA@mail.gmail.com


FAQ