postgres.git / summary / log / commit / refs

commit    0b1f7b527366d8c540796bf8d2f2457bef43638b
Author:   Melanie Plageman <melanieplageman@gmail.com>
Date:     Thu Nov 19 21:16:10 2026 +0000

    Fix WAL-logged CREATE DATABASE with nonstandard pages
    
    RelationCopyStorageUsingBuffer() passed page_std=true when WAL-logging
    every copied relation fork. This allowed WAL insertion to omit the
    region between pd_lower and pd_upper from full-page images and restore
    it as zeroes during replay.
    
    That is safe only for pages using the standard page layout. On
    nonstandard pages, the apparent hole can contain meaningful data,
    causing the primary and standby to diverge. Known affected cases include
    free space maps, visibility maps, and old GIN indexes, though any access
    method using nonstandard pages could be affected.
    
    Losing VM contents can lead to data corruption after promotion. For
    example, a tuple lock on a promoted standby may find the all-frozen bit
    already clear and therefore emit no WAL to clear it. The old primary
    then replays the xmax change without clearing the all-frozen bit,
    retaining the stale bit. This can cause vacuum failures and make
    invisible data visible again.
    
    Only remove the apparent free-space region from WAL when copying a heap
    table or B-tree index, whose pages are known to use the standard layout.
    For other relation types, remove the region only when it contains all
    zeroes, ensuring that replay reconstructs the page without data loss.
    Use a shared bounds helper so that RelationCopyStorageUsingBuffer()
    checks the same region that XLogRecordAssemble() omits.
    
    This may increase WAL volume for access methods other than heap and
    B-tree when the space between pd_lower and pd_upper contains stale data
    that was previously omitted. Such access methods can preserve hole
    removal by zeroing that space.
    
    Reported-by: Matthias van de Meent <boekewurm+postgres@gmail.com>
    Reported-by: Rogers Wang <rogers.ww@qq.com>
    Reviewed-by: surya poondla <suryapoondla4@gmail.com>
    Reviewed-by: Robert Haas <robertmhaas@gmail.com>
    Reviewed-by: Zhijie Hou <houzhijie22@gmail.com>
    Author: Melanie Plageman <melanieplageman@gmail.com>
    Discussion: https://postgr.es/m/flat/CAEze2WgNjODiAiTU18E06_BrRK0nqwJ1kdS_bN61c2_DpFDSnQ%40mail.gmail.com
    Backpatch-through: 15


src/backend/access/transam/xloginsert.c | 13 ++++----- src/backend/commands/dbcommands.c | 19 ++++++++++++- src/backend/storage/buffer/bufmgr.c | 45 ++++++++++++++++++++++++++---- src/include/storage/bufmgr.h | 4 +++ src/include/storage/bufpage.h | 14 ++++++++++ src/include/utils/memutils.h | 14 ++++++++++ src/test/recovery/Makefile | 2 +- src/test/recovery/t/034_create_database.pl | 43 +++++++++++++++++++++++++++- 8 files changed, 137 insertions(+), 17 deletions(-) diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c index 35cc0559f9d..5dd5783b4db 100644 --- a/src/backend/access/transam/xloginsert.c +++ b/src/backend/access/transam/xloginsert.c @@ -626,16 +626,13 @@ XLogRecordAssemble(RmgrId rmid, uint8 info, */ if (regbuf->flags & REGBUF_STANDARD) { - /* Assume we can omit data between pd_lower and pd_upper */ - uint16 lower = ((PageHeader) page)->pd_lower; - uint16 upper = ((PageHeader) page)->pd_upper; + const PageHeaderData *phdr = (const PageHeaderData *) page; - if (lower >= SizeOfPageHeaderData && - upper > lower && - upper <= BLCKSZ) + /* Assume we can omit data between pd_lower and pd_upper */ + if (PageFreeSpaceBoundsAreValid(page)) { - bimg.hole_offset = lower; - cbimg.hole_length = upper - lower; + bimg.hole_offset = phdr->pd_lower; + cbimg.hole_length = phdr->pd_upper - phdr->pd_lower; } else { diff --git a/src/backend/commands/dbcommands.c b/src/backend/commands/dbcommands.c index cedd61ca21c..40de6051afc 100644 --- a/src/backend/commands/dbcommands.c +++ b/src/backend/commands/dbcommands.c @@ -36,6 +36,7 @@ #include "catalog/dependency.h" #include "catalog/indexing.h" #include "catalog/objectaccess.h" +#include "catalog/pg_am_d.h" #include "catalog/pg_authid.h" #include "catalog/pg_collation.h" #include "catalog/pg_database.h" @@ -106,6 +107,7 @@ typedef struct CreateDBRelInfo RelFileNode rnode; /* physical relation identifier */ Oid reloid; /* relation oid */ bool permanent; /* relation is permanent or unlogged */ + bool mainfork_page_std; /* main fork has standard page layout */ } CreateDBRelInfo; @@ -212,7 +214,9 @@ CreateDatabaseUsingWalLog(Oid src_dboid, Oid dst_dboid, LockRelationId(&dstrelid, AccessShareLock); /* Copy relation storage from source to the destination. */ - CreateAndCopyRelationData(srcrnode, dstrnode, relinfo->permanent); + CreateAndCopyRelationDataExtended(srcrnode, dstrnode, + relinfo->permanent, + relinfo->mainfork_page_std); /* Release the relation locks. */ UnlockRelationId(&srcrelid, AccessShareLock); @@ -443,6 +447,19 @@ ScanSourceDatabasePgClassTuple(HeapTupleData *tuple, Oid tbid, Oid dbid, relinfo->permanent = (classForm->relpersistence == RELPERSISTENCE_PERMANENT) ? true : false; + /* + * Heap tables and B-tree indexes are common cases whose main forks are + * known to use the standard page layout. Other access methods may do so + * as well, but some, such as GIN, have legacy page formats that differ + * from their current format. Keep the classification conservative by + * limiting it to heap and B-tree. + */ + relinfo->mainfork_page_std = + (RELKIND_HAS_TABLE_AM(classForm->relkind) && + classForm->relam == HEAP_TABLE_AM_OID) || + (classForm->relkind == RELKIND_INDEX && + classForm->relam == BTREE_AM_OID); + return relinfo; } diff --git a/src/backend/storage/buffer/bufmgr.c b/src/backend/storage/buffer/bufmgr.c index a02814a8f51..3087cd4c9ef 100644 --- a/src/backend/storage/buffer/bufmgr.c +++ b/src/backend/storage/buffer/bufmgr.c @@ -55,6 +55,7 @@ #include "storage/smgr.h" #include "storage/standby.h" #include "utils/memdebug.h" +#include "utils/memutils.h" #include "utils/ps_status.h" #include "utils/rel.h" #include "utils/resowner_private.h" @@ -492,7 +493,8 @@ static void FindAndDropRelFileNodeBuffers(RelFileNode rnode, BlockNumber firstDelBlock); static void RelationCopyStorageUsingBuffer(RelFileNode srcnode, RelFileNode dstnode, - ForkNumber forkNum, bool permanent); + ForkNumber forkNum, bool permanent, + bool page_std); static void AtProcExit_Buffers(int code, Datum arg); static void CheckForBufferLeaks(void); #ifdef USE_ASSERT_CHECKING @@ -3770,8 +3772,9 @@ FlushRelationsAllBuffers(SMgrRelation *smgrs, int nrels) */ static void RelationCopyStorageUsingBuffer(RelFileNode srcnode, - RelFileNode dstnode, - ForkNumber forkNum, bool permanent) + RelFileNode dstnode, + ForkNumber forkNum, bool permanent, + bool page_std) { Buffer srcBuf; Buffer dstBuf; @@ -3836,7 +3839,24 @@ RelationCopyStorageUsingBuffer(RelFileNode srcnode, /* WAL-log the copied page. */ if (use_wal) - log_newpage_buffer(dstBuf, true); + { + bool allow_page_std = page_std; + + /* + * For page layouts we don't recognize, hole removal is still safe + * if the exact range that WAL would omit contains only zeroes. + */ + if (!allow_page_std && PageFreeSpaceBoundsAreValid(dstPage)) + { + PageHeader phdr = (PageHeader) dstPage; + + allow_page_std = + pg_memory_is_all_zeros(dstPage + phdr->pd_lower, + phdr->pd_upper - phdr->pd_lower); + } + + log_newpage_buffer(dstBuf, allow_page_std); + } END_CRIT_SECTION(); @@ -3862,6 +3882,19 @@ RelationCopyStorageUsingBuffer(RelFileNode srcnode, void CreateAndCopyRelationData(RelFileNode src_rnode, RelFileNode dst_rnode, bool permanent) +{ + CreateAndCopyRelationDataExtended(src_rnode, dst_rnode, permanent, false); +} + +/* + * As above, but allow callers that know the main fork's page layout to retain + * full-page image hole removal. + */ +void +CreateAndCopyRelationDataExtended(RelFileNode src_rnode, + RelFileNode dst_rnode, + bool permanent, + bool mainfork_page_std) { RelFileNodeBackend rnode; char relpersistence; @@ -3880,7 +3913,7 @@ CreateAndCopyRelationData(RelFileNode src_rnode, RelFileNode dst_rnode, /* copy main fork. */ RelationCopyStorageUsingBuffer(src_rnode, dst_rnode, MAIN_FORKNUM, - permanent); + permanent, mainfork_page_std); /* copy those extra forks that exist */ for (ForkNumber forkNum = MAIN_FORKNUM + 1; @@ -3899,7 +3932,7 @@ CreateAndCopyRelationData(RelFileNode src_rnode, RelFileNode dst_rnode, /* Copy a fork's data, block by block. */ RelationCopyStorageUsingBuffer(src_rnode, dst_rnode, forkNum, - permanent); + permanent, false); } } diff --git a/src/include/storage/bufmgr.h b/src/include/storage/bufmgr.h index 8e93d315a67..4e7030d509d 100644 --- a/src/include/storage/bufmgr.h +++ b/src/include/storage/bufmgr.h @@ -210,6 +210,10 @@ extern void FlushRelationsAllBuffers(struct SMgrRelationData **smgrs, int nrels) extern void CreateAndCopyRelationData(RelFileNode src_rnode, RelFileNode dst_rnode, bool permanent); +extern void CreateAndCopyRelationDataExtended(RelFileNode src_rnode, + RelFileNode dst_rnode, + bool permanent, + bool mainfork_page_std); extern void FlushDatabaseBuffers(Oid dbid); extern void DropRelFileNodeBuffers(struct SMgrRelationData *smgr_reln, ForkNumber *forkNum, int nforks, BlockNumber *firstDelBlock); diff --git a/src/include/storage/bufpage.h b/src/include/storage/bufpage.h index e9f253f2c8a..badfefdf762 100644 --- a/src/include/storage/bufpage.h +++ b/src/include/storage/bufpage.h @@ -215,6 +215,20 @@ typedef PageHeaderData *PageHeader; */ #define SizeOfPageHeaderData (offsetof(PageHeaderData, pd_linp)) +/* + * Returns true if the page header describes a non-empty, in-bounds free space + * range. This does not prove that the page uses the standard page layout. + */ +static inline bool +PageFreeSpaceBoundsAreValid(Page page) +{ + const PageHeaderData *phdr = (const PageHeaderData *) page; + + return phdr->pd_lower >= SizeOfPageHeaderData && + phdr->pd_upper > phdr->pd_lower && + phdr->pd_upper <= BLCKSZ; +} + /* * PageIsEmpty * returns true iff no itemid has been allocated on the page diff --git a/src/include/utils/memutils.h b/src/include/utils/memutils.h index cbc7bbf00cf..b21ca5af69e 100644 --- a/src/include/utils/memutils.h +++ b/src/include/utils/memutils.h @@ -227,4 +227,18 @@ extern MemoryContext GenerationContextCreate(MemoryContext parent, #define SLAB_DEFAULT_BLOCK_SIZE (8 * 1024) #define SLAB_LARGE_BLOCK_SIZE (8 * 1024 * 1024) +/* Test if a memory region is full of zeroes. */ +static inline bool +pg_memory_is_all_zeros(const void *ptr, size_t len) +{ + const char *p = (const char *) ptr; + + for (size_t i = 0; i < len; i++) + { + if (p[i] != 0) + return false; + } + return true; +} + #endif /* MEMUTILS_H */ diff --git a/src/test/recovery/Makefile b/src/test/recovery/Makefile index c47eee273b7..7c47d078ed8 100644 --- a/src/test/recovery/Makefile +++ b/src/test/recovery/Makefile @@ -9,7 +9,7 @@ # #------------------------------------------------------------------------- -EXTRA_INSTALL=contrib/test_decoding contrib/pg_prewarm +EXTRA_INSTALL=contrib/test_decoding contrib/pg_prewarm contrib/pg_visibility subdir = src/test/recovery top_builddir = ../../.. diff --git a/src/test/recovery/t/034_create_database.pl b/src/test/recovery/t/034_create_database.pl index 4698cbc3915..98a7319295d 100644 --- a/src/test/recovery/t/034_create_database.pl +++ b/src/test/recovery/t/034_create_database.pl @@ -10,9 +10,18 @@ use PostgreSQL::Test::Utils; use Test::More; my $node = PostgreSQL::Test::Cluster->new('node'); -$node->init; +$node->init(allows_streaming => 1); +# Keep the template's pg_class pages in shared buffers between CREATE DATABASE +# and CREATE TABLE. If CREATE TABLE reloads them after eviction, the checkpoint +# can flush its changes even if CREATE DATABASE failed to mark them permanent. +$node->append_conf('postgresql.conf', 'shared_buffers = 16MB'); $node->start; +$node->backup('backup'); +my $standby = PostgreSQL::Test::Cluster->new('standby'); +$standby->init_from_backup($node, 'backup', has_streaming => 1); +$standby->start; + # This checks that any DDLs run on the template database that modify pg_class # are persisted after creating a database from it using the WAL_LOG strategy, # as a direct copy of the template database's pg_class is used in this case. @@ -42,4 +51,36 @@ is($result, "0", "check that there are no tables from template on new database after crash" ); +# Create a table with a populated visibility map in the template database and +# copy it into a second database. +$node->safe_psql($db_template, q{ + CREATE TABLE tab_db_before_create_2 AS + SELECT generate_series(1, 10000) AS a; + VACUUM (FREEZE) tab_db_before_create_2; +}); +my $db_vm = "test_db_2"; +$node->safe_psql("postgres", + "CREATE DATABASE $db_vm STRATEGY WAL_LOG TEMPLATE $db_template;"); +$node->safe_psql($db_vm, "CREATE EXTENSION pg_visibility;"); + +$node->wait_for_catchup($standby); + +my $visibility_map_query = q{ + SELECT blkno, all_visible, all_frozen + FROM pg_visibility_map('tab_db_before_create_2') + ORDER BY blkno; +}; +my $primary_visibility_map = + $node->safe_psql($db_vm, $visibility_map_query); +my $standby_visibility_map = + $standby->safe_psql($db_vm, $visibility_map_query); +my $primary_has_frozen = $node->safe_psql( + $db_vm, + q{SELECT bool_or(all_frozen) + FROM pg_visibility_map('tab_db_before_create_2');}); + +is($primary_has_frozen, 't', 'copied table has an all-frozen page'); +is($standby_visibility_map, $primary_visibility_map, + "copied table visibility map matches standby"); + done_testing(); [parent: e48b96a4fcd1]