pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedHash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
34+ messages / 7 participants
[nested] [flat]
Commits from this thread:
2026-11-18 21c45d45d0 0e278a7dde 573ed87c4c cfdb86434d ed2cc619ac 8becd1123c Fix hash index redo reading a torn primary bucket page.
Related threads (commitfest entry WAL record CRC calculated incorrectly because of underlying buffer modification/7532):
WAL record CRC calculated incorrectly because of underlying buffer modification
* Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
@ 2026-10-29 16:12 Greg Burd <greg@burd.me>
2026-10-30 09:18 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
0 siblings, 2 replies; 34+ messages in thread
From: Greg Burd @ 2026-10-29 16:12 UTC (permalink / raw)
To: pgsql-hackers@lists.postgresql.org; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Vignesh C <vignesh21@gmail.com>; Alexander Lakhin <exclusion@gmail.com>
Hi again,
This is a follow-up to the hash-index WAL CRC thread [1]. Michael asked
that the larger hash rework not ride on that thread, since it is a
refactor that needs its own review attention rather than being buried
under a bug report [2]:
"Could you start a new thread about all that, with all the authors of
this original code in CC at least? Hiding such a large refactoring on
a thread for the CRC failure would not help in terms of attracting the
attention this requires in terms of reviews."
So here it is, on its own thread, with the hash WAL-logging authors in
CC.
Background:
The CRC failure in [1] was that, under wal_consistency_checking='hash',
a standby could stop with "incorrect resource manager data checksum in
record". The cause: hashbucketcleanup(), _hash_squeezebucket() and
_hash_freeovflpage() register the bucket's primary page with
REGBUF_NO_CHANGE while holding only a pin on it (no content lock),
solely so that replay takes a cleanup lock on that page.
XLR_CHECK_CONSISTENCY then forces a full-page image of a page a
concurrent inserter is still free to modify, and the record CRC is
computed over shifting data.
The immediate CRC fix is committed and back-patched to v17 as
27caf4ca5ae5 ("Do not take a full-page image for REGBUF_NO_CHANGE
buffers"): XLogRecordAssemble() no longer forces an image for a
REGBUF_NO_CHANGE buffer, and verifyBackupPageConsistency() skips a
registered block that has no image.
That stops the bleeding but leaves the real problem in place: hash
registers a buffer it does not hold locked or dirty, which breaks the
invariant every other caller of XLogRegisterBuffer() keeps. The plan
proposed (agreed on?) in [1] was three steps:
1. Avoid the CRC problem down to v17, including HEAD. [done: 27caf4ca5ae5]
2. Fix hash so it stops breaking the rule. [0001 here]
3. Remove REGBUF_NO_CHANGE and restore the asserts. [0002 here]
This thread is steps 2 and 3.
0001: Don't register pin-only primary bucket pages in hash WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that a hot-standby scan is not in progress in the bucket, and
cannot start in it, while tuples are removed or moved. Today that lock
is obtained by registering the page (pin-only) with REGBUF_NO_CHANGE.
Redo never reads data from that block; the registration exists only for
the lock.
0001 instead stores the primary bucket page's block number in the main
data of these three records (a new bucket_blkno field) and has replay
read that block and call LockBufferForCleanup() on it directly, at the
same point and in the same order as today. The page is registered only
when the record actually changes it. For the squeeze record this also
removes the pin-only registration of the write page (the case where the
write page is the primary bucket page and nothing is moved onto it).
After 0001, hash registers only buffers it holds exclusively locked and
dirty, and there are no REGBUF_NO_CHANGE users left anywhere in the
tree.
Reading an unregistered block in redo has precedent: nbtree's "pin scan"
did exactly that (XLogReadBufferExtended + LockBufferForCleanup) until
9f83468b353 removed it as no longer needed, not as unsafe. Two
consequences, both benign:
- Recovery prefetch no longer sees the bucket page for these records,
so redo may do one synchronous read of it when it is not already in
shared buffers.
- Block-change consumers (pg_rewind, the WAL summarizer) stop counting
the bucket page as changed by these records. It never was changed,
so this is a correction, not a loss.
The three record formats change, so 0001 bumps XLOG_PAGE_MAGIC; master
only.
Why not just content-lock the primary page, as Jeff asked in [1]?
I looked for a safe placement and it deadlocks where the buffer is
registered. In _hash_freeovflpage() that point is after the metapage is
locked exclusive. A scan of a bucket still being populated by an
incomplete split holds that bucket's primary page share-locked and waits
for the metapage in _hash_get_oldblock_from_newbucket(); VACUUM holds
the metapage and waits for the primary page. Both are buffer content
locks, so the deadlock detector does not see the cycle and a cancel does
not break it. I reproduced it deterministically with an injection point
(3 of 3): pg_cancel_backend() on the VACUUM does nothing and every
insert queues behind the metapage. Taking the bucket lock before the
metapage is read avoids the deadlock, but that variant still costs a
full-page image of the bucket page per checkpoint and holds inserts and
scans on the bucket across the bitmap/metapage work. 0001 as proposed
has neither cost and takes no new lock on the primary page.
0002: Remove REGBUF_NO_CHANGE
With 0001 there are no users of the flag left. 0002 removes it,
restores the unconditional assert in XLogRegisterBuffer() that every
registered buffer is content-locked and dirty, and reverts the two
defensive measures from 27caf4ca5ae5 on master: the XLogRecordAssemble()
special case and the verifyBackupPageConsistency() skip. 27caf4ca5ae5
stays in the back branches, where this hash rework is not applied.
Testing (16-vCPU Debian, cassert, master incl. 27caf4ca5ae5)
- meson test regress, isolation, and recovery (including
recovery/027_stream_regress with
PG_TEST_EXTRA=wal_consistency_checking): all pass with 0001+0002
applied.
- CRC reproduction with 0001+0002, i.e. after 0002 has removed the
step-1 escape and re-added the asserts: primary + streaming standby,
wal_consistency_checking='hash', 8 sessions inserting and deleting on
a single-bucket index with aggressive autovacuum. The standby caught
up with no "incorrect resource manager data checksum", no inconsistent
page, and no assertion failure, 3 of 3. This shows the fix comes from
the hash rework itself, not from the step-1 safety net.
(Earlier, more detailed A/B/C/D runs on the older posting are in [3],
including a hot-standby cursor control showing the cleanup lock still
serializes replay against an in-progress scan.)
Open item from review:
Amit suggested [4] registering bucket_blkno only for the overflow-page
cases, since for a primary-bucket-page record the block is already
known, saving 4 bytes on the common records. I have not made that
change yet; I can in the next version if we agree it is worth the extra
branch in each redo path.
Vignesh contributed a CRC injection-point test on the old thread that
I'd like to review and see how that might fit in and help.
best.
-greg
[1] https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
[2] https://postgr.es/m/auKvDKa3umaD7Hwi@paquier.xyz
[3] https://postgr.es/m/auHpsdSdOXspzuqW@floki
[4] https://postgr.es/m/CAA4eK1+JpYJnUWwrSO7=gs=P3qHkYTrV+gMMPKY-ERv3pHdt-Q@mail.gmail.com
Attachments: download all (2 files, .tar.gz)
v2-0002-Remove-REGBUF_NO_CHANGE.patch (text/plain, 5.2K) download
From 378c674952fb89989cdf0102b4398e54d582cda1 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:38 -0400
Subject: [PATCH v2 2/2] Remove REGBUF_NO_CHANGE
With the previous commit, the hash index AM no longer registers any
pin-only or otherwise-unchanged buffer, so REGBUF_NO_CHANGE has no users
left. Remove the flag and restore the invariant that every registered
buffer is content-locked and dirty: XLogRegisterBuffer() asserts it
unconditionally again.
This also reverts the defensive measures added in 27caf4ca5ae5, which
let a REGBUF_NO_CHANGE buffer skip the full-page image forced by
wal_consistency_checking: XLogRecordAssemble() no longer special-cases
the flag, and verifyBackupPageConsistency() again asserts that a
registered block carries an image. 27caf4ca5ae5 remains in the back
branches, where the hash rework is not applied.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/transam/README | 5 ----
src/backend/access/transam/xloginsert.c | 28 ++++++-----------------
src/backend/access/transam/xlogrecovery.c | 7 +-----
src/include/access/xloginsert.h | 3 ---
4 files changed, 8 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/transam/README b/src/backend/access/transam/README
index 595afa01fa7..231106270fd 100644
--- a/src/backend/access/transam/README
+++ b/src/backend/access/transam/README
@@ -586,11 +586,6 @@ void XLogRegisterBuffer(uint8 block_id, Buffer buf, uint8 flags);
XLogRegisterBufData() is included in the WAL record even if a full-page
image is taken.
- The REGBUF_NO_CHANGE flag indicates that the buffer is registered without
- being modified by this record, and possibly without an exclusive content
- lock. wal_consistency_checking does not force a full-page image for such
- a buffer.
-
void XLogRegisterData(const void *data, int len);
XLogRegisterData is used to include arbitrary data in the WAL record. If
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..987a76c069b 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -256,22 +256,13 @@ XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Assert(begininsert_called);
/*
- * Ordinarily, the buffer should be exclusive-locked (or share-exclusive
- * in case of hint bits) and marked dirty before we get here, otherwise we
- * could end up violating one of the rules in access/transam/README.
- *
- * Some callers intentionally register a clean page and never update that
- * page's LSN; in that case they can pass the flag REGBUF_NO_CHANGE to
- * bypass these checks.
+ * The buffer should be exclusive-locked (or share-exclusive in case of
+ * hint bits) and marked dirty before we get here, otherwise we could end
+ * up violating one of the rules in access/transam/README.
*/
-#ifdef USE_ASSERT_CHECKING
- if (!(flags & REGBUF_NO_CHANGE))
- {
- Assert(BufferIsDirty(buffer));
- Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
- BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
- }
-#endif
+ Assert(BufferIsDirty(buffer));
+ Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
+ BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
if (block_id >= max_registered_block_id)
{
@@ -721,13 +712,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
- *
- * Do not force an image for a REGBUF_NO_CHANGE buffer.
*/
- if (regbuf->flags & REGBUF_NO_CHANGE)
- include_image = needs_backup;
- else
- include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
+ include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..7a1de0567a8 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2488,12 +2488,7 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- /*
- * Blocks registered with REGBUF_NO_CHANGE may have no image, see
- * XLogRecordAssemble(). Nothing to compare for these.
- */
- if (!XLogRecHasBlockImage(record, block_id))
- continue;
+ Assert(XLogRecHasBlockImage(record, block_id));
if (XLogRecBlockImageApply(record, block_id))
{
diff --git a/src/include/access/xloginsert.h b/src/include/access/xloginsert.h
index 86264564ebb..ddb1a85db59 100644
--- a/src/include/access/xloginsert.h
+++ b/src/include/access/xloginsert.h
@@ -38,9 +38,6 @@
* will be skipped) */
#define REGBUF_KEEP_DATA 0x10 /* include data even if a full-page image
* is taken */
-#define REGBUF_NO_CHANGE 0x20 /* intentionally register clean buffer; no
- * image is forced for WAL consistency
- * checking */
/* prototypes for public functions in xloginsert.c: */
extern void XLogBeginInsert(void);
--
2.54.0
v2-0001-Don-t-register-pin-only-primary-bucket-pages-in-h.patch (text/plain, 15.4K) download
From 3ebfc105e5842737c0421412bc0ee821cbe29d0c Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v2 1/2] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the bucket's primary
page, so that a hot standby scan cannot be in progress in the bucket, or
start in it, while tuples are removed or moved. When the primary bucket
page is not itself changed by the record, hashbucketcleanup(),
_hash_squeezebucket() and _hash_freeovflpage() got that lock by
registering the page with REGBUF_NO_CHANGE while holding only a pin on
it. That breaks the rule that a registered buffer is content-locked and
dirtied, and it is why wal_consistency_checking could compute the record
CRC over a page that a concurrent inserter was still changing (fixed on
its own in 27caf4ca5ae5 by not forcing an image for such a buffer).
Instead, store the primary bucket page's block number in the main data
of these three records, and have replay read that block and take the
cleanup lock on it directly, in the same order as before. The page is
no longer registered unless the record changes it. For the squeeze
record this also stops registering the write page when it is the
primary bucket page and is not modified.
With this, hash no longer uses REGBUF_NO_CHANGE.
The three record formats change, so bump XLOG_PAGE_MAGIC.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/hash/README | 9 ++++
src/backend/access/hash/hash.c | 15 +++----
src/backend/access/hash/hash_xlog.c | 56 ++++++++++++++++-------
src/backend/access/hash/hashovfl.c | 61 ++++++++------------------
src/backend/access/rmgrdesc/hashdesc.c | 9 ++--
src/include/access/hash_xlog.h | 18 ++++++--
src/include/access/xlog_internal.h | 2 +-
7 files changed, 93 insertions(+), 77 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..6d9b14e2d21 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record stores its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..fc93d78f6bb 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -902,6 +902,7 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
{
xl_hash_delete xlrec;
+ xlrec.bucket_blkno = bucket_blkno;
xlrec.clear_dead_marking = clear_dead_marking;
xlrec.is_primary_bucket_page = (buf == bucket_buf);
@@ -909,17 +910,11 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * If buf is an overflow page, the primary bucket page is not
+ * changed and we hold only a pin on it, so it is not
+ * registered. Replay takes a cleanup lock on bucket_blkno
+ * instead.
*/
- if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
-
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..04eb8e17dd4 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -469,6 +469,33 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on the primary bucket page of the bucket that a
+ * squeeze or delete record operates on, when that page is not one of the
+ * pages the record changes and so is not registered in it.
+ *
+ * This serializes replay against scans on a hot standby, which pin the
+ * primary bucket page for their whole duration; see the comments in the
+ * callers. The page is not modified, so nothing is done with it besides
+ * locking it. block_id must be a block of the same index registered in
+ * the record.
+ */
+static Buffer
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id,
+ BlockNumber bucket_blkno)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ Buffer buf;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -493,11 +520,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -617,14 +640,19 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ {
+ /* block 1 is absent if the primary bucket page is not modified */
+ if (XLogRecHasBlockRef(record, 1))
+ action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ action = BLK_NOTFOUND;
+ }
+ }
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -851,11 +879,7 @@ hash_xlog_delete(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..2bc9015c223 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -657,6 +657,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
{
xl_hash_squeeze_page xlrec;
+ xlrec.bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
xlrec.ntups = nitups;
@@ -667,42 +668,21 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Register only the pages this record changes. The primary bucket
+ * page is registered only if it is the write page and is modified;
+ * otherwise we may hold only a pin on it, and replay takes a cleanup
+ * lock on bucket_blkno instead.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
-
- if (nitups > 0)
+ if (mod_wbuf)
{
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
- {
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(1, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(1, itups[i], tups_size[i]);
+ }
}
XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
@@ -991,6 +971,7 @@ readpage:
{
xl_hash_move_page_contents xlrec;
+ xlrec.bucket_blkno = bucket_blkno;
xlrec.ntups = nitups;
xlrec.is_prim_bucket_same_wrt = (wbuf == bucket_buf);
@@ -998,17 +979,11 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Replay takes a cleanup
+ * lock on bucket_blkno instead.
*/
- if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
-
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
XLogRegisterBufData(1, itup_offsets,
nitups * sizeof(OffsetNumber));
diff --git a/src/backend/access/rmgrdesc/hashdesc.c b/src/backend/access/rmgrdesc/hashdesc.c
index 593013afe9c..6988b6a82c3 100644
--- a/src/backend/access/rmgrdesc/hashdesc.c
+++ b/src/backend/access/rmgrdesc/hashdesc.c
@@ -80,7 +80,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_move_page_contents *xlrec = (xl_hash_move_page_contents *) rec;
- appendStringInfo(buf, "ntups %d, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, ntups %d, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F');
break;
@@ -89,7 +90,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_squeeze_page *xlrec = (xl_hash_squeeze_page *) rec;
- appendStringInfo(buf, "prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
+ appendStringInfo(buf, "bucket_blkno %u, prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
+ xlrec->bucket_blkno,
xlrec->prevblkno,
xlrec->nextblkno,
xlrec->ntups,
@@ -101,7 +103,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_delete *xlrec = (xl_hash_delete *) rec;
- appendStringInfo(buf, "clear_dead_marking %c, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, clear_dead_marking %c, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->clear_dead_marking ? 'T' : 'F',
xlrec->is_primary_bucket_page ? 'T' : 'F');
break;
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..9d762ff70d3 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,12 +129,15 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page containing moved tuples
* Backup Blk 2: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered; replay takes a cleanup lock on
+ * bucket_blkno instead.
*/
typedef struct xl_hash_move_page_contents
{
+ BlockNumber bucket_blkno; /* primary bucket page */
uint16 ntups;
bool is_prim_bucket_same_wrt; /* true if the page to which
* tuples are moved is same as
@@ -149,16 +152,20 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
+ * Backup Blk 1: page containing tuples moved from freed overflow page, if
+ * it is modified
* Backup Blk 2: freed overflow page
* Backup Blk 3: page previous to the freed overflow page
* Backup Blk 4: page next to the freed overflow page
* Backup Blk 5: bitmap page containing info of freed overflow page
* Backup Blk 6: meta page
+ *
+ * The primary bucket page is registered only as block 1, when it is the
+ * modified write page; otherwise replay takes a cleanup lock on bucket_blkno.
*/
typedef struct xl_hash_squeeze_page
{
+ BlockNumber bucket_blkno; /* primary bucket page */
BlockNumber prevblkno;
BlockNumber nextblkno;
uint16 ntups;
@@ -179,11 +186,14 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page from which tuples are deleted
+ *
+ * If block 1 is not the primary bucket page, replay takes a cleanup lock on
+ * bucket_blkno, which is not registered.
*/
typedef struct xl_hash_delete
{
+ BlockNumber bucket_blkno; /* primary bucket page */
bool clear_dead_marking; /* true if this operation clears
* LH_PAGE_HAS_DEAD_TUPLES flag */
bool is_primary_bucket_page; /* true if the operation is for
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
--
2.54.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-10-30 09:18 ` vignesh C <vignesh21@gmail.com>
1 sibling, 0 replies; 34+ messages in thread
From: vignesh C @ 2026-10-30 09:18 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; +Cc: pgsql-hackers@lists.postgresql.org, Amit Kapila <amit.kapila16@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>
On Thu, 29 Oct 2026 at 21:42, Greg Burd <greg@burd.me> wrote:
>
> Open item from review:
>
> Amit suggested [4] registering bucket_blkno only for the overflow-page
> cases, since for a primary-bucket-page record the block is already
> known, saving 4 bytes on the common records. I have not made that
> change yet; I can in the next version if we agree it is worth the extra
> branch in each redo path.
Yes, that would be better. The
v3-0002-Append-the-hash-primary-bucket-block-number-to-WA.patch patch
has the changes for the same. The v3-0001 is the same as v2-0001
posted by Greg. Please merge it if you feel the changes are ok.
I did not include the v2-0002-Remove-REGBUF_NO_CHANGE patch as we can
get to it once we bring the first patch into committable shape.
Regards,
Vignesh
Attachments: download all (2 files, .tar.gz)
v3-0002-Append-the-hash-primary-bucket-block-number-to-WA.patch (application/octet-stream, 11.7K) download
From 22005e0e3e674261bb30c7b694cc471616461926 Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Fri, 30 Oct 2026 10:58:12 +0530
Subject: [PATCH v3 2/2] Append the hash primary bucket block number to WAL
records only when needed
The previous commit stores the primary bucket page's block number in
xl_hash_delete, xl_hash_move_page_contents and xl_hash_squeeze_page.
Replay only uses it when the primary bucket page is not one of the pages
the record changes, so in the other cases the four bytes are wasted.
Remove the field from the three structs, and append the block number to
the main data of the record only when the primary bucket page is not
registered or modified by it. Replay reads it from just after the
fixed-size struct. The structs return to their previous sizes, and
the records are no larger than before in the common case.
Suggested by Amit Kapila.
---
src/backend/access/hash/README | 2 +-
src/backend/access/hash/hash.c | 8 +++++---
src/backend/access/hash/hash_xlog.c | 19 ++++++++++++-------
src/backend/access/hash/hashovfl.c | 17 +++++++++++------
src/backend/access/rmgrdesc/hashdesc.c | 9 +++------
src/include/access/hash_xlog.h | 19 +++++++++++--------
6 files changed, 43 insertions(+), 31 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index 6d9b14e2d21..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -647,7 +647,7 @@ that no scan on a hot standby is in progress in the bucket or can start in
it while tuples are removed or moved; such a scan could otherwise miss
tuples or return them twice. When the primary bucket page is not one of
the pages the record changes, the operation holds only a pin on it, so it
-is not registered in the record. The record stores its block number
+is not registered in the record. The record then carries its block number
instead, and replay locks that block directly.
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index fc93d78f6bb..9dbd008fed9 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -902,7 +902,6 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
{
xl_hash_delete xlrec;
- xlrec.bucket_blkno = bucket_blkno;
xlrec.clear_dead_marking = clear_dead_marking;
xlrec.is_primary_bucket_page = (buf == bucket_buf);
@@ -912,9 +911,12 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
/*
* If buf is an overflow page, the primary bucket page is not
* changed and we hold only a pin on it, so it is not
- * registered. Replay takes a cleanup lock on bucket_blkno
- * instead.
+ * registered. Append its block number instead, and replay
+ * takes a cleanup lock on it. It is not needed otherwise.
*/
+ if (!xlrec.is_primary_bucket_page)
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 04eb8e17dd4..1484c12d948 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -472,7 +472,9 @@ hash_xlog_split_complete(XLogReaderState *record)
/*
* Take a cleanup lock on the primary bucket page of the bucket that a
* squeeze or delete record operates on, when that page is not one of the
- * pages the record changes and so is not registered in it.
+ * pages the record changes and so is not registered in it. Its block number
+ * is stored in the main data of the record, right after the fixed-size struct
+ * of rec_size bytes.
*
* This serializes replay against scans on a hot standby, which pin the
* primary bucket page for their whole duration; see the comments in the
@@ -481,13 +483,16 @@ hash_xlog_split_complete(XLogReaderState *record)
* the record.
*/
static Buffer
-hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id,
- BlockNumber bucket_blkno)
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
{
RelFileLocator rlocator;
ForkNumber forknum;
+ BlockNumber bucket_blkno;
Buffer buf;
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
RBM_NORMAL, InvalidBuffer);
@@ -520,7 +525,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashMovePageContents);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -646,13 +651,13 @@ hash_xlog_squeeze_page(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, SizeOfHashSqueezePage);
action = BLK_NOTFOUND;
}
}
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -879,7 +884,7 @@ hash_xlog_delete(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashDelete);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index 2bc9015c223..a5a40ba6a91 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -656,8 +656,8 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
- xlrec.bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
xlrec.ntups = nitups;
@@ -670,9 +670,12 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/*
* Register only the pages this record changes. The primary bucket
* page is registered only if it is the write page and is modified;
- * otherwise we may hold only a pin on it, and replay takes a cleanup
- * lock on bucket_blkno instead.
+ * otherwise we may hold only a pin on it, so append its block number
+ * and replay takes a cleanup lock on it.
*/
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
if (mod_wbuf)
{
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
@@ -971,7 +974,6 @@ readpage:
{
xl_hash_move_page_contents xlrec;
- xlrec.bucket_blkno = bucket_blkno;
xlrec.ntups = nitups;
xlrec.is_prim_bucket_same_wrt = (wbuf == bucket_buf);
@@ -981,9 +983,12 @@ readpage:
/*
* If wbuf is an overflow page, the primary bucket
* page is not changed and we hold only a pin on it,
- * so it is not registered. Replay takes a cleanup
- * lock on bucket_blkno instead.
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
+ if (!xlrec.is_prim_bucket_same_wrt)
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
XLogRegisterBufData(1, itup_offsets,
nitups * sizeof(OffsetNumber));
diff --git a/src/backend/access/rmgrdesc/hashdesc.c b/src/backend/access/rmgrdesc/hashdesc.c
index 6988b6a82c3..593013afe9c 100644
--- a/src/backend/access/rmgrdesc/hashdesc.c
+++ b/src/backend/access/rmgrdesc/hashdesc.c
@@ -80,8 +80,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_move_page_contents *xlrec = (xl_hash_move_page_contents *) rec;
- appendStringInfo(buf, "bucket_blkno %u, ntups %d, is_primary %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "ntups %d, is_primary %c",
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F');
break;
@@ -90,8 +89,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_squeeze_page *xlrec = (xl_hash_squeeze_page *) rec;
- appendStringInfo(buf, "bucket_blkno %u, prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
xlrec->prevblkno,
xlrec->nextblkno,
xlrec->ntups,
@@ -103,8 +101,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_delete *xlrec = (xl_hash_delete *) rec;
- appendStringInfo(buf, "bucket_blkno %u, clear_dead_marking %c, is_primary %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "clear_dead_marking %c, is_primary %c",
xlrec->clear_dead_marking ? 'T' : 'F',
xlrec->is_primary_bucket_page ? 'T' : 'F');
break;
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 9d762ff70d3..c4a55f071bc 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -132,12 +132,13 @@ typedef struct xl_hash_split_complete
* Backup Blk 1: page containing moved tuples
* Backup Blk 2: page from which tuples will be removed
*
- * The primary bucket page is not registered; replay takes a cleanup lock on
- * bucket_blkno instead.
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
- BlockNumber bucket_blkno; /* primary bucket page */
uint16 ntups;
bool is_prim_bucket_same_wrt; /* true if the page to which
* tuples are moved is same as
@@ -161,11 +162,12 @@ typedef struct xl_hash_move_page_contents
* Backup Blk 6: meta page
*
* The primary bucket page is registered only as block 1, when it is the
- * modified write page; otherwise replay takes a cleanup lock on bucket_blkno.
+ * modified write page. Otherwise the block number of the primary bucket page
+ * follows the struct as a BlockNumber, and replay takes a cleanup lock on that
+ * block.
*/
typedef struct xl_hash_squeeze_page
{
- BlockNumber bucket_blkno; /* primary bucket page */
BlockNumber prevblkno;
BlockNumber nextblkno;
uint16 ntups;
@@ -188,12 +190,13 @@ typedef struct xl_hash_squeeze_page
*
* Backup Blk 1: page from which tuples are deleted
*
- * If block 1 is not the primary bucket page, replay takes a cleanup lock on
- * bucket_blkno, which is not registered.
+ * If block 1 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
- BlockNumber bucket_blkno; /* primary bucket page */
bool clear_dead_marking; /* true if this operation clears
* LH_PAGE_HAS_DEAD_TUPLES flag */
bool is_primary_bucket_page; /* true if the operation is for
--
2.55.0
v3-0001-Don-t-register-pin-only-primary-bucket-pages-in-h.patch (application/octet-stream, 15.0K) download
From d56e8151715ef71acd59fc1867196772e26aab5f Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Tue, 27 Oct 2026 13:16:47 -0400
Subject: [PATCH v3 1/2] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the bucket's primary
page, so that a hot standby scan cannot be in progress in the bucket, or
start in it, while tuples are removed or moved. When the primary bucket
page is not itself changed by the record, hashbucketcleanup(),
_hash_squeezebucket() and _hash_freeovflpage() got that lock by
registering the page with REGBUF_NO_CHANGE while holding only a pin on
it. That breaks the rule that a registered buffer is content-locked and
dirtied, and it is why wal_consistency_checking could compute the record
CRC over a page that a concurrent inserter was still changing.
Instead, store the primary bucket page's block number in the main data
of these three records, and have replay read that block and take the
cleanup lock on it directly, in the same order as before. The page is
no longer registered unless the record changes it. For the squeeze
record this also stops registering the write page when it is the
primary bucket page and is not modified.
With this, hash no longer uses REGBUF_NO_CHANGE.
The three record formats change, so bump XLOG_PAGE_MAGIC.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/hash/README | 9 ++++
src/backend/access/hash/hash.c | 15 +++----
src/backend/access/hash/hash_xlog.c | 56 ++++++++++++++++-------
src/backend/access/hash/hashovfl.c | 61 ++++++++------------------
src/backend/access/rmgrdesc/hashdesc.c | 9 ++--
src/include/access/hash_xlog.h | 18 ++++++--
src/include/access/xlog_internal.h | 2 +-
7 files changed, 93 insertions(+), 77 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..6d9b14e2d21 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record stores its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..fc93d78f6bb 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -902,6 +902,7 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
{
xl_hash_delete xlrec;
+ xlrec.bucket_blkno = bucket_blkno;
xlrec.clear_dead_marking = clear_dead_marking;
xlrec.is_primary_bucket_page = (buf == bucket_buf);
@@ -909,17 +910,11 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * If buf is an overflow page, the primary bucket page is not
+ * changed and we hold only a pin on it, so it is not
+ * registered. Replay takes a cleanup lock on bucket_blkno
+ * instead.
*/
- if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
-
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..04eb8e17dd4 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -469,6 +469,33 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on the primary bucket page of the bucket that a
+ * squeeze or delete record operates on, when that page is not one of the
+ * pages the record changes and so is not registered in it.
+ *
+ * This serializes replay against scans on a hot standby, which pin the
+ * primary bucket page for their whole duration; see the comments in the
+ * callers. The page is not modified, so nothing is done with it besides
+ * locking it. block_id must be a block of the same index registered in
+ * the record.
+ */
+static Buffer
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id,
+ BlockNumber bucket_blkno)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ Buffer buf;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -493,11 +520,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -617,14 +640,19 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ {
+ /* block 1 is absent if the primary bucket page is not modified */
+ if (XLogRecHasBlockRef(record, 1))
+ action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ action = BLK_NOTFOUND;
+ }
+ }
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -851,11 +879,7 @@ hash_xlog_delete(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..2bc9015c223 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -657,6 +657,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
{
xl_hash_squeeze_page xlrec;
+ xlrec.bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
xlrec.ntups = nitups;
@@ -667,42 +668,21 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Register only the pages this record changes. The primary bucket
+ * page is registered only if it is the write page and is modified;
+ * otherwise we may hold only a pin on it, and replay takes a cleanup
+ * lock on bucket_blkno instead.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
-
- if (nitups > 0)
+ if (mod_wbuf)
{
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
- {
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(1, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(1, itups[i], tups_size[i]);
+ }
}
XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
@@ -991,6 +971,7 @@ readpage:
{
xl_hash_move_page_contents xlrec;
+ xlrec.bucket_blkno = bucket_blkno;
xlrec.ntups = nitups;
xlrec.is_prim_bucket_same_wrt = (wbuf == bucket_buf);
@@ -998,17 +979,11 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Replay takes a cleanup
+ * lock on bucket_blkno instead.
*/
- if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
-
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
XLogRegisterBufData(1, itup_offsets,
nitups * sizeof(OffsetNumber));
diff --git a/src/backend/access/rmgrdesc/hashdesc.c b/src/backend/access/rmgrdesc/hashdesc.c
index 593013afe9c..6988b6a82c3 100644
--- a/src/backend/access/rmgrdesc/hashdesc.c
+++ b/src/backend/access/rmgrdesc/hashdesc.c
@@ -80,7 +80,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_move_page_contents *xlrec = (xl_hash_move_page_contents *) rec;
- appendStringInfo(buf, "ntups %d, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, ntups %d, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F');
break;
@@ -89,7 +90,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_squeeze_page *xlrec = (xl_hash_squeeze_page *) rec;
- appendStringInfo(buf, "prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
+ appendStringInfo(buf, "bucket_blkno %u, prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
+ xlrec->bucket_blkno,
xlrec->prevblkno,
xlrec->nextblkno,
xlrec->ntups,
@@ -101,7 +103,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_delete *xlrec = (xl_hash_delete *) rec;
- appendStringInfo(buf, "clear_dead_marking %c, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, clear_dead_marking %c, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->clear_dead_marking ? 'T' : 'F',
xlrec->is_primary_bucket_page ? 'T' : 'F');
break;
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..9d762ff70d3 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,12 +129,15 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page containing moved tuples
* Backup Blk 2: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered; replay takes a cleanup lock on
+ * bucket_blkno instead.
*/
typedef struct xl_hash_move_page_contents
{
+ BlockNumber bucket_blkno; /* primary bucket page */
uint16 ntups;
bool is_prim_bucket_same_wrt; /* true if the page to which
* tuples are moved is same as
@@ -149,16 +152,20 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
+ * Backup Blk 1: page containing tuples moved from freed overflow page, if
+ * it is modified
* Backup Blk 2: freed overflow page
* Backup Blk 3: page previous to the freed overflow page
* Backup Blk 4: page next to the freed overflow page
* Backup Blk 5: bitmap page containing info of freed overflow page
* Backup Blk 6: meta page
+ *
+ * The primary bucket page is registered only as block 1, when it is the
+ * modified write page; otherwise replay takes a cleanup lock on bucket_blkno.
*/
typedef struct xl_hash_squeeze_page
{
+ BlockNumber bucket_blkno; /* primary bucket page */
BlockNumber prevblkno;
BlockNumber nextblkno;
uint16 ntups;
@@ -179,11 +186,14 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page from which tuples are deleted
+ *
+ * If block 1 is not the primary bucket page, replay takes a cleanup lock on
+ * bucket_blkno, which is not registered.
*/
typedef struct xl_hash_delete
{
+ BlockNumber bucket_blkno; /* primary bucket page */
bool clear_dead_marking; /* true if this operation clears
* LH_PAGE_HAS_DEAD_TUPLES flag */
bool is_primary_bucket_page; /* true if the operation is for
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
--
2.55.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-10-30 11:48 ` vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
1 sibling, 1 reply; 34+ messages in thread
From: vignesh C @ 2026-10-30 11:48 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; +Cc: pgsql-hackers@lists.postgresql.org, Amit Kapila <amit.kapila16@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>
On Thu, 29 Oct 2026 at 21:42, Greg Burd <greg@burd.me> wrote:
>
> Hi again,
>
> This is a follow-up to the hash-index WAL CRC thread [1]. Michael asked
> that the larger hash rework not ride on that thread, since it is a
> refactor that needs its own review attention rather than being buried
> under a bug report [2]:
>
> "Could you start a new thread about all that, with all the authors of
> this original code in CC at least? Hiding such a large refactoring on
> a thread for the CRC failure would not help in terms of attracting the
> attention this requires in terms of reviews."
>
> So here it is, on its own thread, with the hash WAL-logging authors in
> CC.
>
> Background:
>
> The CRC failure in [1] was that, under wal_consistency_checking='hash',
> a standby could stop with "incorrect resource manager data checksum in
> record". The cause: hashbucketcleanup(), _hash_squeezebucket() and
> _hash_freeovflpage() register the bucket's primary page with
> REGBUF_NO_CHANGE while holding only a pin on it (no content lock),
> solely so that replay takes a cleanup lock on that page.
> XLR_CHECK_CONSISTENCY then forces a full-page image of a page a
> concurrent inserter is still free to modify, and the record CRC is
> computed over shifting data.
>
> The immediate CRC fix is committed and back-patched to v17 as
> 27caf4ca5ae5 ("Do not take a full-page image for REGBUF_NO_CHANGE
> buffers"): XLogRecordAssemble() no longer forces an image for a
> REGBUF_NO_CHANGE buffer, and verifyBackupPageConsistency() skips a
> registered block that has no image.
>
> That stops the bleeding but leaves the real problem in place: hash
> registers a buffer it does not hold locked or dirty, which breaks the
> invariant every other caller of XLogRegisterBuffer() keeps. The plan
> proposed (agreed on?) in [1] was three steps:
>
> 1. Avoid the CRC problem down to v17, including HEAD. [done: 27caf4ca5ae5]
> 2. Fix hash so it stops breaking the rule. [0001 here]
> 3. Remove REGBUF_NO_CHANGE and restore the asserts. [0002 here]
>
> This thread is steps 2 and 3.
>
> 0001: Don't register pin-only primary bucket pages in hash WAL records
>
> Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
> XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
> page so that a hot-standby scan is not in progress in the bucket, and
> cannot start in it, while tuples are removed or moved. Today that lock
> is obtained by registering the page (pin-only) with REGBUF_NO_CHANGE.
> Redo never reads data from that block; the registration exists only for
> the lock.
The patches change the WAL records, and XLOG_PAGE_MAGIC cannot be
bumped in a minor release, so I looked at what happens if they are
backpatched. I built the base REL_18_STABLE, REL_18 + 0001, + 0002,
and + 0003 (attached, adapted for REL_18: the squeeze code there lacks
the locals present on master, so 0001 computes mod_wbuf itself) and
ran them against each other with streaming replication and crash
recovery, with wal_consistency_checking = 'hash' and VACUUM of hash
indexes in which every shape of the three records occurs.
Results (primary -> standby; all rows and index/heap scans checked):
p3 -> base works
base -> p3 works
p1 -> base fails: failed to locate backup block with ID 0
p2 -> base fails: same
base -> p1 fails: replay reads bucket_blkno that old
records do not have
base -> p2 fails: same
So 0001 and 0002 on their own are not safe in a minor release, in
either direction: a) a new primary writes records without block 0,
which an old standby cannot replay b) a new standby, or crash recovery
after upgrade, replays records written by an old server, which have
block 0 and no appended block number.
I'm not sure if we should back patch this patch. If we plan to back
patch, here is a patch for the same. The 0001 and 0002 are the same
patches as the v3 version posted in previous mail (rebased for PG18)
and 0003 has the backward compatible patch to fix them.
Thoughts?
Regards,
Vignesh
Attachments: download all (3 files, .tar.gz)
v3_REL18-0002-Append-the-hash-primary-bucket-block-number.patch (application/octet-stream, 11.7K) download
From 1c507086f9c9957815b4e44dcee826389aabb34c Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Fri, 30 Oct 2026 13:21:15 +0530
Subject: [PATCH v3_REL18 2/3] Append the hash primary bucket block number to
WAL records only when needed
The previous commit stores the primary bucket page's block number in
xl_hash_delete, xl_hash_move_page_contents and xl_hash_squeeze_page.
Replay only uses it when the primary bucket page is not one of the pages
the record changes, so in the other cases the four bytes are wasted.
Remove the field from the three structs, and append the block number to
the main data of the record only when the primary bucket page is not
registered or modified by it. Replay reads it from just after the
fixed-size struct. The structs return to their previous sizes, and
the records are no larger than before in the common case.
Suggested by Amit Kapila.
---
src/backend/access/hash/README | 2 +-
src/backend/access/hash/hash.c | 8 +++++---
src/backend/access/hash/hash_xlog.c | 19 ++++++++++++-------
src/backend/access/hash/hashovfl.c | 17 +++++++++++------
src/backend/access/rmgrdesc/hashdesc.c | 9 +++------
src/include/access/hash_xlog.h | 19 +++++++++++--------
6 files changed, 43 insertions(+), 31 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index 6d9b14e2d21..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -647,7 +647,7 @@ that no scan on a hot standby is in progress in the bucket or can start in
it while tuples are removed or moved; such a scan could otherwise miss
tuples or return them twice. When the primary bucket page is not one of
the pages the record changes, the operation holds only a pin on it, so it
-is not registered in the record. The record stores its block number
+is not registered in the record. The record then carries its block number
instead, and replay locks that block directly.
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index d71fc75ea0c..0aa60619269 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -823,7 +823,6 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
xl_hash_delete xlrec;
XLogRecPtr recptr;
- xlrec.bucket_blkno = bucket_blkno;
xlrec.clear_dead_marking = clear_dead_marking;
xlrec.is_primary_bucket_page = (buf == bucket_buf);
@@ -833,9 +832,12 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
/*
* If buf is an overflow page, the primary bucket page is not
* changed and we hold only a pin on it, so it is not
- * registered. Replay takes a cleanup lock on bucket_blkno
- * instead.
+ * registered. Append its block number instead, and replay
+ * takes a cleanup lock on it. It is not needed otherwise.
*/
+ if (!xlrec.is_primary_bucket_page)
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index b9ebdafae4c..e2edfe1afc0 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -474,7 +474,9 @@ hash_xlog_split_complete(XLogReaderState *record)
/*
* Take a cleanup lock on the primary bucket page of the bucket that a
* squeeze or delete record operates on, when that page is not one of the
- * pages the record changes and so is not registered in it.
+ * pages the record changes and so is not registered in it. Its block number
+ * is stored in the main data of the record, right after the fixed-size struct
+ * of rec_size bytes.
*
* This serializes replay against scans on a hot standby, which pin the
* primary bucket page for their whole duration; see the comments in the
@@ -483,13 +485,16 @@ hash_xlog_split_complete(XLogReaderState *record)
* the record.
*/
static Buffer
-hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id,
- BlockNumber bucket_blkno)
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
{
RelFileLocator rlocator;
ForkNumber forknum;
+ BlockNumber bucket_blkno;
Buffer buf;
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
RBM_NORMAL, InvalidBuffer);
@@ -522,7 +527,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashMovePageContents);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -649,13 +654,13 @@ hash_xlog_squeeze_page(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, SizeOfHashSqueezePage);
action = BLK_NOTFOUND;
}
}
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -883,7 +888,7 @@ hash_xlog_delete(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashDelete);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index 3bec464efae..cbd299acc08 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -645,11 +645,11 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
XLogRecPtr recptr;
int i;
bool mod_wbuf;
- xlrec.bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
xlrec.ntups = nitups;
@@ -665,9 +665,12 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/*
* Register only the pages this record changes. The primary bucket
* page is registered only if it is the write page and is modified;
- * otherwise we may hold only a pin on it, and replay takes a cleanup
- * lock on bucket_blkno instead.
+ * otherwise we may hold only a pin on it, so append its block number
+ * and replay takes a cleanup lock on it.
*/
+ if (!(xlrec.is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
if (mod_wbuf)
{
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
@@ -963,7 +966,6 @@ readpage:
XLogRecPtr recptr;
xl_hash_move_page_contents xlrec;
- xlrec.bucket_blkno = bucket_blkno;
xlrec.ntups = nitups;
xlrec.is_prim_bucket_same_wrt = (wbuf == bucket_buf);
@@ -973,9 +975,12 @@ readpage:
/*
* If wbuf is an overflow page, the primary bucket
* page is not changed and we hold only a pin on it,
- * so it is not registered. Replay takes a cleanup
- * lock on bucket_blkno instead.
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
+ if (!xlrec.is_prim_bucket_same_wrt)
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
XLogRegisterBufData(1, itup_offsets,
nitups * sizeof(OffsetNumber));
diff --git a/src/backend/access/rmgrdesc/hashdesc.c b/src/backend/access/rmgrdesc/hashdesc.c
index 8872c521e69..75f43a91520 100644
--- a/src/backend/access/rmgrdesc/hashdesc.c
+++ b/src/backend/access/rmgrdesc/hashdesc.c
@@ -76,8 +76,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_move_page_contents *xlrec = (xl_hash_move_page_contents *) rec;
- appendStringInfo(buf, "bucket_blkno %u, ntups %d, is_primary %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "ntups %d, is_primary %c",
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F');
break;
@@ -86,8 +85,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_squeeze_page *xlrec = (xl_hash_squeeze_page *) rec;
- appendStringInfo(buf, "bucket_blkno %u, prevblkno %u, nextblkno %u, ntups %d, is_primary %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "prevblkno %u, nextblkno %u, ntups %d, is_primary %c",
xlrec->prevblkno,
xlrec->nextblkno,
xlrec->ntups,
@@ -98,8 +96,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_delete *xlrec = (xl_hash_delete *) rec;
- appendStringInfo(buf, "bucket_blkno %u, clear_dead_marking %c, is_primary %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "clear_dead_marking %c, is_primary %c",
xlrec->clear_dead_marking ? 'T' : 'F',
xlrec->is_primary_bucket_page ? 'T' : 'F');
break;
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 8580d5dbead..731bff5fb28 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -132,12 +132,13 @@ typedef struct xl_hash_split_complete
* Backup Blk 1: page containing moved tuples
* Backup Blk 2: page from which tuples will be removed
*
- * The primary bucket page is not registered; replay takes a cleanup lock on
- * bucket_blkno instead.
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
- BlockNumber bucket_blkno; /* primary bucket page */
uint16 ntups;
bool is_prim_bucket_same_wrt; /* true if the page to which
* tuples are moved is same as
@@ -161,11 +162,12 @@ typedef struct xl_hash_move_page_contents
* Backup Blk 6: meta page
*
* The primary bucket page is registered only as block 1, when it is the
- * modified write page; otherwise replay takes a cleanup lock on bucket_blkno.
+ * modified write page. Otherwise the block number of the primary bucket page
+ * follows the struct as a BlockNumber, and replay takes a cleanup lock on that
+ * block.
*/
typedef struct xl_hash_squeeze_page
{
- BlockNumber bucket_blkno; /* primary bucket page */
BlockNumber prevblkno;
BlockNumber nextblkno;
uint16 ntups;
@@ -188,12 +190,13 @@ typedef struct xl_hash_squeeze_page
*
* Backup Blk 1: page from which tuples are deleted
*
- * If block 1 is not the primary bucket page, replay takes a cleanup lock on
- * bucket_blkno, which is not registered.
+ * If block 1 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
- BlockNumber bucket_blkno; /* primary bucket page */
bool clear_dead_marking; /* true if this operation clears
* LH_PAGE_HAS_DEAD_TUPLES flag */
bool is_primary_bucket_page; /* true if the operation is for
--
2.55.0
v3_REL18-0001-Don-t-register-pin-only-primary-bucket-page.patch (application/octet-stream, 14.9K) download
From bd7b2c4dd9ef4fba1f41b6842510f5818c16d7d9 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Tue, 27 Oct 2026 13:16:47 -0400
Subject: [PATCH v3_REL18 1/3] Don't register pin-only primary bucket pages in
hash WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the bucket's primary
page, so that a hot standby scan cannot be in progress in the bucket, or
start in it, while tuples are removed or moved. When the primary bucket
page is not itself changed by the record, hashbucketcleanup(),
_hash_squeezebucket() and _hash_freeovflpage() got that lock by
registering the page with REGBUF_NO_CHANGE while holding only a pin on
it. That breaks the rule that a registered buffer is content-locked and
dirtied, and it is why wal_consistency_checking could compute the record
CRC over a page that a concurrent inserter was still changing.
Instead, store the primary bucket page's block number in the main data
of these three records, and have replay read that block and take the
cleanup lock on it directly, in the same order as before. The page is
no longer registered unless the record changes it. For the squeeze
record this also stops registering the write page when it is the
primary bucket page and is not modified.
With this, hash no longer uses REGBUF_NO_CHANGE.
The three record formats change, so bump XLOG_PAGE_MAGIC.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/hash/README | 9 ++++
src/backend/access/hash/hash.c | 15 ++----
src/backend/access/hash/hash_xlog.c | 56 ++++++++++++++------
src/backend/access/hash/hashovfl.c | 71 ++++++++------------------
src/backend/access/rmgrdesc/hashdesc.c | 9 ++--
src/include/access/hash_xlog.h | 18 +++++--
6 files changed, 94 insertions(+), 84 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..6d9b14e2d21 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record stores its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index a7d7f2f6d32..d71fc75ea0c 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -823,6 +823,7 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
xl_hash_delete xlrec;
XLogRecPtr recptr;
+ xlrec.bucket_blkno = bucket_blkno;
xlrec.clear_dead_marking = clear_dead_marking;
xlrec.is_primary_bucket_page = (buf == bucket_buf);
@@ -830,17 +831,11 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * If buf is an overflow page, the primary bucket page is not
+ * changed and we hold only a pin on it, so it is not
+ * registered. Replay takes a cleanup lock on bucket_blkno
+ * instead.
*/
- if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
-
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index d4cb6246b48..b9ebdafae4c 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -471,6 +471,33 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on the primary bucket page of the bucket that a
+ * squeeze or delete record operates on, when that page is not one of the
+ * pages the record changes and so is not registered in it.
+ *
+ * This serializes replay against scans on a hot standby, which pin the
+ * primary bucket page for their whole duration; see the comments in the
+ * callers. The page is not modified, so nothing is done with it besides
+ * locking it. block_id must be a block of the same index registered in
+ * the record.
+ */
+static Buffer
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id,
+ BlockNumber bucket_blkno)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ Buffer buf;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -495,11 +522,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -620,14 +643,19 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ {
+ /* block 1 is absent if the primary bucket page is not modified */
+ if (XLogRecHasBlockRef(record, 1))
+ action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ action = BLK_NOTFOUND;
+ }
+ }
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -855,11 +883,7 @@ hash_xlog_delete(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index 4f5fd3b2837..3bec464efae 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -647,63 +647,37 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
xl_hash_squeeze_page xlrec;
XLogRecPtr recptr;
int i;
- bool mod_wbuf = false;
+ bool mod_wbuf;
+ xlrec.bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
xlrec.ntups = nitups;
xlrec.is_prim_bucket_same_wrt = (wbuf == bucketbuf);
xlrec.is_prev_bucket_same_wrt = (wbuf == prevbuf);
+ /* wbuf is modified iff tuples are moved onto it or it is prevbuf */
+ mod_wbuf = (nitups > 0 || xlrec.is_prev_bucket_same_wrt);
+
XLogBeginInsert();
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Register only the pages this record changes. The primary bucket
+ * page is registered only if it is the write page and is modified;
+ * otherwise we may hold only a pin on it, and replay takes a cleanup
+ * lock on bucket_blkno instead.
*/
- if (!xlrec.is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
-
- if (xlrec.ntups > 0)
+ if (mod_wbuf)
{
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
-
- /* Remember that wbuf is modified. */
- mod_wbuf = true;
-
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (xlrec.is_prim_bucket_same_wrt || xlrec.is_prev_bucket_same_wrt)
- {
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(xlrec.ntups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!xlrec.is_prev_bucket_same_wrt)
- {
- wbuf_flags |= REGBUF_NO_CHANGE;
- }
- else
+ if (nitups > 0)
{
- /* Remember that wbuf is modified. */
- mod_wbuf = true;
+ XLogRegisterBufData(1, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (i = 0; i < nitups; i++)
+ XLogRegisterBufData(1, itups[i], tups_size[i]);
}
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
}
XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
@@ -989,6 +963,7 @@ readpage:
XLogRecPtr recptr;
xl_hash_move_page_contents xlrec;
+ xlrec.bucket_blkno = bucket_blkno;
xlrec.ntups = nitups;
xlrec.is_prim_bucket_same_wrt = (wbuf == bucket_buf);
@@ -996,17 +971,11 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Replay takes a cleanup
+ * lock on bucket_blkno instead.
*/
- if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
-
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
XLogRegisterBufData(1, itup_offsets,
nitups * sizeof(OffsetNumber));
diff --git a/src/backend/access/rmgrdesc/hashdesc.c b/src/backend/access/rmgrdesc/hashdesc.c
index 75f43a91520..8872c521e69 100644
--- a/src/backend/access/rmgrdesc/hashdesc.c
+++ b/src/backend/access/rmgrdesc/hashdesc.c
@@ -76,7 +76,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_move_page_contents *xlrec = (xl_hash_move_page_contents *) rec;
- appendStringInfo(buf, "ntups %d, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, ntups %d, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F');
break;
@@ -85,7 +86,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_squeeze_page *xlrec = (xl_hash_squeeze_page *) rec;
- appendStringInfo(buf, "prevblkno %u, nextblkno %u, ntups %d, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, prevblkno %u, nextblkno %u, ntups %d, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->prevblkno,
xlrec->nextblkno,
xlrec->ntups,
@@ -96,7 +98,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_delete *xlrec = (xl_hash_delete *) rec;
- appendStringInfo(buf, "clear_dead_marking %c, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, clear_dead_marking %c, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->clear_dead_marking ? 'T' : 'F',
xlrec->is_primary_bucket_page ? 'T' : 'F');
break;
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 5d4671dc4c1..8580d5dbead 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,12 +129,15 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page containing moved tuples
* Backup Blk 2: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered; replay takes a cleanup lock on
+ * bucket_blkno instead.
*/
typedef struct xl_hash_move_page_contents
{
+ BlockNumber bucket_blkno; /* primary bucket page */
uint16 ntups;
bool is_prim_bucket_same_wrt; /* true if the page to which
* tuples are moved is same as
@@ -149,16 +152,20 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
+ * Backup Blk 1: page containing tuples moved from freed overflow page, if
+ * it is modified
* Backup Blk 2: freed overflow page
* Backup Blk 3: page previous to the freed overflow page
* Backup Blk 4: page next to the freed overflow page
* Backup Blk 5: bitmap page containing info of freed overflow page
* Backup Blk 6: meta page
+ *
+ * The primary bucket page is registered only as block 1, when it is the
+ * modified write page; otherwise replay takes a cleanup lock on bucket_blkno.
*/
typedef struct xl_hash_squeeze_page
{
+ BlockNumber bucket_blkno; /* primary bucket page */
BlockNumber prevblkno;
BlockNumber nextblkno;
uint16 ntups;
@@ -179,11 +186,14 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page from which tuples are deleted
+ *
+ * If block 1 is not the primary bucket page, replay takes a cleanup lock on
+ * bucket_blkno, which is not registered.
*/
typedef struct xl_hash_delete
{
+ BlockNumber bucket_blkno; /* primary bucket page */
bool clear_dead_marking; /* true if this operation clears
* LH_PAGE_HAS_DEAD_TUPLES flag */
bool is_primary_bucket_page; /* true if the operation is for
--
2.55.0
v3_REL18-0003-Hash-keep-the-WAL-of-the-previous-changes-r.patch (application/octet-stream, 13.1K) download
From cc80ad12f7415bdcaa7cb57b775c117e7d141ada Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Fri, 30 Oct 2026 13:22:41 +0530
Subject: [PATCH v3_REL18 3/3] Hash: keep the WAL of the previous changes
replayable across minor versions
The previous two commits stop registering the primary bucket page in
XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and XLOG_HASH_SQUEEZE_PAGE
records unless the record changes it, and append its block number to the
record instead. In a back branch, WAL generated by earlier minor versions
must still be replayable, and so must WAL generated by this one on a standby
that has not been upgraded.
Replay: accept both forms. A record that registers the primary bucket page
as block 0, as written by older minor versions, is replayed through that
block, as before; so is a squeeze record that registers the write page, when
it is the primary bucket page, as an unmodified block 1. Otherwise the page
is found through the appended block number.
Write: older minor versions cannot replay a record without block 0 (they
fail with "failed to locate backup block with ID 0 in WAL record"), so the
primary bucket page is still registered as before, and its block number not
appended, guarded by HASH_WAL_REGISTER_BUCKET_PAGE, until it is acceptable to
stop doing so. The macro must be 1 while standbys of older minor versions
are supported, in which case the records are the same as those of the older
minor versions, and may be 0 once all servers replaying the WAL have this
change. The CRC problem under wal_consistency_checking
does not depend on this: the registered block is REGBUF_NO_CHANGE, for which
no image is taken.
XLOG_PAGE_MAGIC is not changed.
---
src/backend/access/hash/README | 6 ++--
src/backend/access/hash/hash.c | 15 +++++++--
src/backend/access/hash/hash_xlog.c | 26 +++++++++++----
src/backend/access/hash/hashovfl.c | 39 ++++++++++++++++++++--
src/include/access/hash_xlog.h | 50 ++++++++++++++++++++++-------
5 files changed, 111 insertions(+), 25 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index 7774e1d2fe0..eef866d9b22 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -647,8 +647,10 @@ that no scan on a hot standby is in progress in the bucket or can start in
it while tuples are removed or moved; such a scan could otherwise miss
tuples or return them twice. When the primary bucket page is not one of
the pages the record changes, the operation holds only a pin on it, so it
-is not registered in the record. The record then carries its block number
-instead, and replay locks that block directly.
+is not required in the record. The record then carries its block number
+instead, and replay locks that block directly. Records written by older
+minor versions register the page instead, and replay accepts both forms.
+See HASH_WAL_REGISTER_BUCKET_PAGE in hash_xlog.h.
Other Notes
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 0aa60619269..261487a7fb0 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -832,11 +832,22 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
/*
* If buf is an overflow page, the primary bucket page is not
* changed and we hold only a pin on it, so it is not
- * registered. Append its block number instead, and replay
- * takes a cleanup lock on it. It is not needed otherwise.
+ * registered, unless older standbys must be supported. Append
+ * its block number instead, and replay takes a cleanup lock on
+ * it. It is not needed otherwise.
*/
+#if HASH_WAL_REGISTER_BUCKET_PAGE
+ /* for standbys that predate the block number, see hash_xlog.h */
+ if (!xlrec.is_primary_bucket_page)
+ {
+ uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
+
+ XLogRegisterBuffer(0, bucket_buf, flags);
+ }
+#else
if (!xlrec.is_primary_bucket_page)
XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+#endif
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
XLogRegisterBufData(1, deletable,
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e2edfe1afc0..511b1dcdd46 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -473,16 +473,20 @@ hash_xlog_split_complete(XLogReaderState *record)
/*
* Take a cleanup lock on the primary bucket page of the bucket that a
- * squeeze or delete record operates on, when that page is not one of the
- * pages the record changes and so is not registered in it. Its block number
- * is stored in the main data of the record, right after the fixed-size struct
- * of rec_size bytes.
+ * move-page-contents, squeeze or delete record operates on, when that page is
+ * not one of the pages the record changes.
*
* This serializes replay against scans on a hot standby, which pin the
* primary bucket page for their whole duration; see the comments in the
* callers. The page is not modified, so nothing is done with it besides
- * locking it. block_id must be a block of the same index registered in
- * the record.
+ * locking it.
+ *
+ * Records written by older minor versions, and by this one while
+ * HASH_WAL_REGISTER_BUCKET_PAGE is set, register the primary bucket page as
+ * block 0; for those, the lock is taken through block 0. Otherwise the
+ * block number of the page is stored in the main data of the record, right
+ * after the fixed-size struct of rec_size bytes, and block_id must be a block
+ * of the same index registered in the record.
*/
static Buffer
hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
@@ -492,7 +496,15 @@ hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
BlockNumber bucket_blkno;
Buffer buf;
- Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ if (XLogRecHasBlockRef(record, 0))
+ {
+ /* primary bucket page registered, as older minor versions do */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &buf);
+ return buf;
+ }
+
+ if (XLogRecGetDataLen(record) < rec_size + sizeof(BlockNumber))
+ elog(PANIC, "hash WAL record has neither the primary bucket page nor its block number");
memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index cbd299acc08..a8ba27957c7 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -645,7 +645,9 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+#if !HASH_WAL_REGISTER_BUCKET_PAGE
BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
+#endif
XLogRecPtr recptr;
int i;
bool mod_wbuf;
@@ -666,10 +668,20 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* Register only the pages this record changes. The primary bucket
* page is registered only if it is the write page and is modified;
* otherwise we may hold only a pin on it, so append its block number
- * and replay takes a cleanup lock on it.
+ * and replay takes a cleanup lock on it, unless older standbys must
+ * be supported, see hash_xlog.h.
*/
+#if HASH_WAL_REGISTER_BUCKET_PAGE
+ if (!xlrec.is_prim_bucket_same_wrt)
+ {
+ uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
+
+ XLogRegisterBuffer(0, bucketbuf, flags);
+ }
+#else
if (!(xlrec.is_prim_bucket_same_wrt && mod_wbuf))
XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+#endif
if (mod_wbuf)
{
@@ -682,6 +694,16 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterBufData(1, itups[i], tups_size[i]);
}
}
+#if HASH_WAL_REGISTER_BUCKET_PAGE
+ else if (xlrec.is_prim_bucket_same_wrt)
+ {
+ /*
+ * The primary page is the write page and nothing moves onto it.
+ * Older minor versions expect it as block 1, to lock it.
+ */
+ XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD | REGBUF_NO_CHANGE);
+ }
+#endif
XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
@@ -975,11 +997,22 @@ readpage:
/*
* If wbuf is an overflow page, the primary bucket
* page is not changed and we hold only a pin on it,
- * so it is not registered. Append its block number
- * instead, and replay takes a cleanup lock on it.
+ * so it is not registered, unless older standbys must
+ * be supported. Append its block number instead, and
+ * replay takes a cleanup lock on it.
*/
+#if HASH_WAL_REGISTER_BUCKET_PAGE
+ /* for standbys that predate the block number */
+ if (!xlrec.is_prim_bucket_same_wrt)
+ {
+ int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
+
+ XLogRegisterBuffer(0, bucket_buf, flags);
+ }
+#else
if (!xlrec.is_prim_bucket_same_wrt)
XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+#endif
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
XLogRegisterBufData(1, itup_offsets,
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 731bff5fb28..0512841d4c5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -21,6 +21,30 @@
/* Number of buffers required for XLOG_HASH_SQUEEZE_PAGE operation */
#define HASH_XLOG_FREE_OVFL_BUFS 6
+/*
+ * Compatibility with other minor versions.
+ *
+ * Records of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
+ * XLOG_HASH_SQUEEZE_PAGE written by minor versions before the one that
+ * introduced the appended block number of the primary bucket page register
+ * that page as a block reference, only so that replay can take a cleanup lock
+ * on it: as block 0 if it is not the page the record changes, and, for
+ * XLOG_HASH_SQUEEZE_PAGE, as an unmodified block 1 if it is the write page
+ * and nothing is moved onto it. Replay accepts both forms: if the record
+ * registers the page, that block is used, otherwise the appended block number
+ * is.
+ *
+ * A minor version without that replay code cannot replay a record that does
+ * not register the page; it fails with "failed to locate backup block with ID
+ * 0 in WAL record". While standbys running such versions must be supported,
+ * keep writing the block reference, by leaving this set to 1; the records are
+ * then the same as those of the older minor versions. Setting it to 0 stops
+ * registering the page and appends its block number instead, and requires that
+ * all servers replaying this WAL are at least at the version that introduced
+ * it.
+ */
+#define HASH_WAL_REGISTER_BUCKET_PAGE 1
+
/*
* XLOG records for hash operations
*/
@@ -132,10 +156,11 @@ typedef struct xl_hash_split_complete
* Backup Blk 1: page containing moved tuples
* Backup Blk 2: page from which tuples will be removed
*
- * The primary bucket page is not registered. If it is not the page moved to
- * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
- * page follows the struct as a BlockNumber, and replay takes a cleanup lock
- * on that block.
+ * If it is not the page moved to (is_prim_bucket_same_wrt is false), the
+ * primary bucket page is either registered as block 0, as long as
+ * HASH_WAL_REGISTER_BUCKET_PAGE is set and in records written by older minor
+ * versions, or else its block number follows the struct as a BlockNumber.
+ * Replay takes a cleanup lock on that page.
*/
typedef struct xl_hash_move_page_contents
{
@@ -161,10 +186,12 @@ typedef struct xl_hash_move_page_contents
* Backup Blk 5: bitmap page containing info of freed overflow page
* Backup Blk 6: meta page
*
- * The primary bucket page is registered only as block 1, when it is the
- * modified write page. Otherwise the block number of the primary bucket page
- * follows the struct as a BlockNumber, and replay takes a cleanup lock on that
- * block.
+ * The primary bucket page is registered as block 1 when it is the write page
+ * and is modified. Otherwise it is registered as block 0 (or, if it is the
+ * write page, as an unmodified block 1), as long as
+ * HASH_WAL_REGISTER_BUCKET_PAGE is set and in records written by older minor
+ * versions, or else its block number follows the struct as a BlockNumber.
+ * Replay takes a cleanup lock on that page.
*/
typedef struct xl_hash_squeeze_page
{
@@ -191,9 +218,10 @@ typedef struct xl_hash_squeeze_page
* Backup Blk 1: page from which tuples are deleted
*
* If block 1 is not the primary bucket page (is_primary_bucket_page is
- * false), the block number of the primary bucket page follows the struct as a
- * BlockNumber, and replay takes a cleanup lock on that block. The primary
- * bucket page is not registered.
+ * false), the primary bucket page is either registered as block 0, as long as
+ * HASH_WAL_REGISTER_BUCKET_PAGE is set and in records written by older minor
+ * versions, or else its block number follows the struct as a BlockNumber.
+ * Replay takes a cleanup lock on that page.
*/
typedef struct xl_hash_delete
{
--
2.55.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
@ 2026-10-30 17:21 ` Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 34+ messages in thread
From: Greg Burd @ 2026-10-30 17:21 UTC (permalink / raw)
To: vignesh21@gmail.com; +Cc: pgsql-hackers@lists.postgresql.org; amit.kapila16@gmail.com; michael@paquier.xyz; pgsql@j-davis.com; exclusion@gmail.com
On Fri, 30 Oct 2026 17:18:34 +0530, vignesh C <vignesh21@gmail.com> wrote:
> On Thu, 29 Oct 2026 at 21:42, Greg Burd <greg@burd.me> wrote:
> >
> > Hi again,
> >
> > This is a follow-up to the hash-index WAL CRC thread [1]. Michael asked
> > that the larger hash rework not ride on that thread, since it is a
> > refactor that needs its own review attention rather than being buried
> > under a bug report [2]:
> >
> > "Could you start a new thread about all that, with all the authors of
> > this original code in CC at least? Hiding such a large refactoring on
> > a thread for the CRC failure would not help in terms of attracting the
> > attention this requires in terms of reviews."
> >
> > So here it is, on its own thread, with the hash WAL-logging authors in
> > CC.
> >
> > Background:
> >
> > The CRC failure in [1] was that, under wal_consistency_checking='hash',
> > a standby could stop with "incorrect resource manager data checksum in
> > record". The cause: hashbucketcleanup(), _hash_squeezebucket() and
> > _hash_freeovflpage() register the bucket's primary page with
> > REGBUF_NO_CHANGE while holding only a pin on it (no content lock),
> > solely so that replay takes a cleanup lock on that page.
> > XLR_CHECK_CONSISTENCY then forces a full-page image of a page a
> > concurrent inserter is still free to modify, and the record CRC is
> > computed over shifting data.
> >
> > The immediate CRC fix is committed and back-patched to v17 as
> > 27caf4ca5ae5 ("Do not take a full-page image for REGBUF_NO_CHANGE
> > buffers"): XLogRecordAssemble() no longer forces an image for a
> > REGBUF_NO_CHANGE buffer, and verifyBackupPageConsistency() skips a
> > registered block that has no image.
> >
> > That stops the bleeding but leaves the real problem in place: hash
> > registers a buffer it does not hold locked or dirty, which breaks the
> > invariant every other caller of XLogRegisterBuffer() keeps. The plan
> > proposed (agreed on?) in [1] was three steps:
> >
> > 1. Avoid the CRC problem down to v17, including HEAD. [done: 27caf4ca5ae5]
> > 2. Fix hash so it stops breaking the rule. [0001 here]
> > 3. Remove REGBUF_NO_CHANGE and restore the asserts. [0002 here]
> >
> > This thread is steps 2 and 3.
> >
> > 0001: Don't register pin-only primary bucket pages in hash WAL records
> >
> > Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
> > XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
> > page so that a hot-standby scan is not in progress in the bucket, and
> > cannot start in it, while tuples are removed or moved. Today that lock
> > is obtained by registering the page (pin-only) with REGBUF_NO_CHANGE.
> > Redo never reads data from that block; the registration exists only for
> > the lock.
Hi Vignesh,
Thanks for picking this up and for the two things you added: splitting
the four-byte saving out as its own patch, and the back-branch analysis.
On the structure: I've taken your v3-0001 (same as my v2-0001) and your
v3-0002 (append the block number only when the primary page is not
registered) as the base, and built the rest of the series on top. The
attached v3 is:
0001 Don't register pin-only primary bucket pages in hash WAL records
(unchanged from your v3-0001 / my v2-0001)
0002 Append the hash primary bucket block number to WAL records only
when needed (your v3-0002, Amit's suggestion)
0003 Add a recovery test for the hash WAL pin-only bucket page fix
0004 Remove REGBUF_NO_CHANGE
0002 keeps the records the same size as today in the common case, so I
think it belongs in the series rather than as a follow-up; thanks for
writing it.
0003 is the recovery test. It turns the CRC window into a deterministic
one with a general, test-only injection point in XLogRecordAssemble(),
right after the record CRC is computed and before the record is copied
into the WAL buffers. The injection point's argument names the record
as "rmid/info/mainlen", so the test waits on exactly the overflow-page
XLOG_HASH_DELETE (whose main data carries the appended bucket block
number, so it is distinguishable from the primary-page delete), lets a
concurrent INSERT change the pin-only primary bucket page, then crashes
and checks that pg_waldump and crash recovery both accept the WAL. This
is your test from the CRC thread, carried forward: the record selector
moved from the REGBUF_NO_CHANGE buffer count (which the rework zeroes)
to the main-data length so it still picks the right record after the
rework. I kept you as a co-author.
0004 removes REGBUF_NO_CHANGE and restores the unconditional assert in
XLogRegisterBuffer(), and reverts the two defensive measures from
27caf4ca5ae5 on master.
> The patches change the WAL records, and XLOG_PAGE_MAGIC cannot be
> bumped in a minor release, so I looked at what happens if they are
> backpatched. I built the base REL_18_STABLE, REL_18 + 0001, + 0002,
> and + 0003 (attached, adapted for REL_18: the squeeze code there lacks
> the locals present on master, so 0001 computes mod_wbuf itself) and
> ran them against each other with streaming replication and crash
> recovery, with wal_consistency_checking = 'hash' and VACUUM of hash
> indexes in which every shape of the three records occurs.
On your back-branch question: I don't think we should back-patch this.
27caf4ca5ae5 already fixes the actual CRC failure down to v17, so the
back branches are correct as they stand. The rework here is a cleanup
that changes three WAL record formats and bumps XLOG_PAGE_MAGIC, which,
as your p1/p2-vs-base runs show, is not compatible across a minor
release in either direction. That is exactly the kind of change we keep
to master. So I'd leave the back branches on 27caf4ca5ae5 and not carry
your v3_REL18-0003 compatibility shim; it is good to have proven the
incompatibility, but the conclusion is "master only", which 0001 already
says in its XLOG_PAGE_MAGIC bump.
One fix went into 0002 after a first CI round: pulling the primary
bucket block number out of the record struct into its own data segment
needs one more slot than XLogEnsureRecordSpace() reserved in
_hash_freeovflpage() and the move-page-contents path, so a 32-bit build
hit "too much WAL data" during a hash VACUUM that packs more tuples per
WAL record than a 64-bit build does. 0002 now reserves the extra
segment.
Patches 0001-0004 attached, against current master.
best.
-greg
Attachments: download all (4 files, .tar.gz)
v3-0002-Append-the-hash-primary-bucket-block-number-to-WA.patch (text/plain, 13.3K) download
From 69b23919f242c6b777737479578abb629c035160 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 09:13:23 -0400
Subject: [PATCH v3 2/4] Append the hash primary bucket block number to WAL
records only when needed
The previous commit stores the primary bucket page's block number in
xl_hash_delete, xl_hash_move_page_contents and xl_hash_squeeze_page.
Replay only uses it when the primary bucket page is not one of the pages
the record changes, so in the other cases the four bytes are wasted.
Remove the field from the three structs, and append the block number to
the main data of the record only when the primary bucket page is not
registered or modified by it. Replay reads it from just after the
fixed-size struct. The structs return to their previous sizes, and the
records are no larger than before in the common case.
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Author: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm2L_0eJ1yKbp4OM9XdyrGHpyK3iU49nbc5hCRe3F+MPjg@mail.gmail.com
---
src/backend/access/hash/README | 2 +-
src/backend/access/hash/hash.c | 8 ++++---
src/backend/access/hash/hash_xlog.c | 19 ++++++++++------
src/backend/access/hash/hashovfl.c | 31 +++++++++++++++++---------
src/backend/access/rmgrdesc/hashdesc.c | 9 +++-----
src/include/access/hash_xlog.h | 19 +++++++++-------
6 files changed, 53 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index 6d9b14e2d21..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -647,7 +647,7 @@ that no scan on a hot standby is in progress in the bucket or can start in
it while tuples are removed or moved; such a scan could otherwise miss
tuples or return them twice. When the primary bucket page is not one of
the pages the record changes, the operation holds only a pin on it, so it
-is not registered in the record. The record stores its block number
+is not registered in the record. The record then carries its block number
instead, and replay locks that block directly.
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index fc93d78f6bb..9dbd008fed9 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -902,7 +902,6 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
{
xl_hash_delete xlrec;
- xlrec.bucket_blkno = bucket_blkno;
xlrec.clear_dead_marking = clear_dead_marking;
xlrec.is_primary_bucket_page = (buf == bucket_buf);
@@ -912,9 +911,12 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
/*
* If buf is an overflow page, the primary bucket page is not
* changed and we hold only a pin on it, so it is not
- * registered. Replay takes a cleanup lock on bucket_blkno
- * instead.
+ * registered. Append its block number instead, and replay
+ * takes a cleanup lock on it. It is not needed otherwise.
*/
+ if (!xlrec.is_primary_bucket_page)
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 04eb8e17dd4..1484c12d948 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -472,7 +472,9 @@ hash_xlog_split_complete(XLogReaderState *record)
/*
* Take a cleanup lock on the primary bucket page of the bucket that a
* squeeze or delete record operates on, when that page is not one of the
- * pages the record changes and so is not registered in it.
+ * pages the record changes and so is not registered in it. Its block number
+ * is stored in the main data of the record, right after the fixed-size struct
+ * of rec_size bytes.
*
* This serializes replay against scans on a hot standby, which pin the
* primary bucket page for their whole duration; see the comments in the
@@ -481,13 +483,16 @@ hash_xlog_split_complete(XLogReaderState *record)
* the record.
*/
static Buffer
-hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id,
- BlockNumber bucket_blkno)
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
{
RelFileLocator rlocator;
ForkNumber forknum;
+ BlockNumber bucket_blkno;
Buffer buf;
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
RBM_NORMAL, InvalidBuffer);
@@ -520,7 +525,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashMovePageContents);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -646,13 +651,13 @@ hash_xlog_squeeze_page(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, SizeOfHashSqueezePage);
action = BLK_NOTFOUND;
}
}
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -879,7 +884,7 @@ hash_xlog_delete(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashDelete);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index 2bc9015c223..91781f7c2b0 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,8 +660,8 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
- xlrec.bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
xlrec.ntups = nitups;
@@ -670,9 +674,12 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/*
* Register only the pages this record changes. The primary bucket
* page is registered only if it is the write page and is modified;
- * otherwise we may hold only a pin on it, and replay takes a cleanup
- * lock on bucket_blkno instead.
+ * otherwise we may hold only a pin on it, so append its block number
+ * and replay takes a cleanup lock on it.
*/
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
if (mod_wbuf)
{
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
@@ -946,10 +953,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -971,7 +980,6 @@ readpage:
{
xl_hash_move_page_contents xlrec;
- xlrec.bucket_blkno = bucket_blkno;
xlrec.ntups = nitups;
xlrec.is_prim_bucket_same_wrt = (wbuf == bucket_buf);
@@ -981,9 +989,12 @@ readpage:
/*
* If wbuf is an overflow page, the primary bucket
* page is not changed and we hold only a pin on it,
- * so it is not registered. Replay takes a cleanup
- * lock on bucket_blkno instead.
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
+ if (!xlrec.is_prim_bucket_same_wrt)
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
XLogRegisterBufData(1, itup_offsets,
nitups * sizeof(OffsetNumber));
diff --git a/src/backend/access/rmgrdesc/hashdesc.c b/src/backend/access/rmgrdesc/hashdesc.c
index 6988b6a82c3..593013afe9c 100644
--- a/src/backend/access/rmgrdesc/hashdesc.c
+++ b/src/backend/access/rmgrdesc/hashdesc.c
@@ -80,8 +80,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_move_page_contents *xlrec = (xl_hash_move_page_contents *) rec;
- appendStringInfo(buf, "bucket_blkno %u, ntups %d, is_primary %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "ntups %d, is_primary %c",
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F');
break;
@@ -90,8 +89,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_squeeze_page *xlrec = (xl_hash_squeeze_page *) rec;
- appendStringInfo(buf, "bucket_blkno %u, prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
xlrec->prevblkno,
xlrec->nextblkno,
xlrec->ntups,
@@ -103,8 +101,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_delete *xlrec = (xl_hash_delete *) rec;
- appendStringInfo(buf, "bucket_blkno %u, clear_dead_marking %c, is_primary %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "clear_dead_marking %c, is_primary %c",
xlrec->clear_dead_marking ? 'T' : 'F',
xlrec->is_primary_bucket_page ? 'T' : 'F');
break;
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 9d762ff70d3..12fc5f50ea5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -132,12 +132,13 @@ typedef struct xl_hash_split_complete
* Backup Blk 1: page containing moved tuples
* Backup Blk 2: page from which tuples will be removed
*
- * The primary bucket page is not registered; replay takes a cleanup lock on
- * bucket_blkno instead.
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
- BlockNumber bucket_blkno; /* primary bucket page */
uint16 ntups;
bool is_prim_bucket_same_wrt; /* true if the page to which
* tuples are moved is same as
@@ -161,11 +162,12 @@ typedef struct xl_hash_move_page_contents
* Backup Blk 6: meta page
*
* The primary bucket page is registered only as block 1, when it is the
- * modified write page; otherwise replay takes a cleanup lock on bucket_blkno.
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
- BlockNumber bucket_blkno; /* primary bucket page */
BlockNumber prevblkno;
BlockNumber nextblkno;
uint16 ntups;
@@ -188,12 +190,13 @@ typedef struct xl_hash_squeeze_page
*
* Backup Blk 1: page from which tuples are deleted
*
- * If block 1 is not the primary bucket page, replay takes a cleanup lock on
- * bucket_blkno, which is not registered.
+ * If block 1 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
- BlockNumber bucket_blkno; /* primary bucket page */
bool clear_dead_marking; /* true if this operation clears
* LH_PAGE_HAS_DEAD_TUPLES flag */
bool is_primary_bucket_page; /* true if the operation is for
--
2.54.0
v3-0003-Add-a-recovery-test-for-the-hash-WAL-pin-only-buc.patch (text/plain, 11.4K) download
From 78c4c34714e48a72e1aa1b6e32396b16e12fce1d Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v3 3/4] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/061_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 +++
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_vacuum_insert_crc.pl | 176 ++++++++++++++++++
3 files changed, 199 insertions(+)
create mode 100644 src/test/recovery/t/061_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..5051031df56 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_vacuum_insert_crc.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_vacuum_insert_crc.pl b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..f658299c7a0
--- /dev/null
+++ b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
@@ -0,0 +1,176 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'});
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike($stderr, qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.54.0
v3-0004-Remove-REGBUF_NO_CHANGE.patch (text/plain, 5.2K) download
From 925228f4734f471663ddb2f9764447fb8899291a Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:17:46 -0400
Subject: [PATCH v3 4/4] Remove REGBUF_NO_CHANGE
With the previous commits, the hash index AM no longer registers any
pin-only or otherwise-unchanged buffer, so REGBUF_NO_CHANGE has no users
left. Remove the flag and restore the invariant that every registered
buffer is content-locked and dirty: XLogRegisterBuffer() asserts it
unconditionally again.
This also reverts the defensive measures added in 27caf4ca5ae5, which
let a REGBUF_NO_CHANGE buffer skip the full-page image forced by
wal_consistency_checking: XLogRecordAssemble() no longer special-cases
the flag, and verifyBackupPageConsistency() again asserts that a
registered block carries an image. 27caf4ca5ae5 remains in the back
branches, where this hash rework is not applied.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/transam/README | 5 ----
src/backend/access/transam/xloginsert.c | 28 ++++++-----------------
src/backend/access/transam/xlogrecovery.c | 7 +-----
src/include/access/xloginsert.h | 3 ---
4 files changed, 8 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/transam/README b/src/backend/access/transam/README
index 595afa01fa7..231106270fd 100644
--- a/src/backend/access/transam/README
+++ b/src/backend/access/transam/README
@@ -586,11 +586,6 @@ void XLogRegisterBuffer(uint8 block_id, Buffer buf, uint8 flags);
XLogRegisterBufData() is included in the WAL record even if a full-page
image is taken.
- The REGBUF_NO_CHANGE flag indicates that the buffer is registered without
- being modified by this record, and possibly without an exclusive content
- lock. wal_consistency_checking does not force a full-page image for such
- a buffer.
-
void XLogRegisterData(const void *data, int len);
XLogRegisterData is used to include arbitrary data in the WAL record. If
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index cd3359434e1..2d031e38594 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -257,22 +257,13 @@ XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Assert(begininsert_called);
/*
- * Ordinarily, the buffer should be exclusive-locked (or share-exclusive
- * in case of hint bits) and marked dirty before we get here, otherwise we
- * could end up violating one of the rules in access/transam/README.
- *
- * Some callers intentionally register a clean page and never update that
- * page's LSN; in that case they can pass the flag REGBUF_NO_CHANGE to
- * bypass these checks.
+ * The buffer should be exclusive-locked (or share-exclusive in case of
+ * hint bits) and marked dirty before we get here, otherwise we could end
+ * up violating one of the rules in access/transam/README.
*/
-#ifdef USE_ASSERT_CHECKING
- if (!(flags & REGBUF_NO_CHANGE))
- {
- Assert(BufferIsDirty(buffer));
- Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
- BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
- }
-#endif
+ Assert(BufferIsDirty(buffer));
+ Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
+ BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
if (block_id >= max_registered_block_id)
{
@@ -722,13 +713,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
- *
- * Do not force an image for a REGBUF_NO_CHANGE buffer.
*/
- if (regbuf->flags & REGBUF_NO_CHANGE)
- include_image = needs_backup;
- else
- include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
+ include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..7a1de0567a8 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2488,12 +2488,7 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- /*
- * Blocks registered with REGBUF_NO_CHANGE may have no image, see
- * XLogRecordAssemble(). Nothing to compare for these.
- */
- if (!XLogRecHasBlockImage(record, block_id))
- continue;
+ Assert(XLogRecHasBlockImage(record, block_id));
if (XLogRecBlockImageApply(record, block_id))
{
diff --git a/src/include/access/xloginsert.h b/src/include/access/xloginsert.h
index 86264564ebb..ddb1a85db59 100644
--- a/src/include/access/xloginsert.h
+++ b/src/include/access/xloginsert.h
@@ -38,9 +38,6 @@
* will be skipped) */
#define REGBUF_KEEP_DATA 0x10 /* include data even if a full-page image
* is taken */
-#define REGBUF_NO_CHANGE 0x20 /* intentionally register clean buffer; no
- * image is forced for WAL consistency
- * checking */
/* prototypes for public functions in xloginsert.c: */
extern void XLogBeginInsert(void);
--
2.54.0
v3-0001-Don-t-register-pin-only-primary-bucket-pages-in-h.patch (text/plain, 15.4K) download
From ad33f03e52ea021331a4431ed6bff64335674b9c Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v3 1/4] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the bucket's primary
page, so that a hot standby scan cannot be in progress in the bucket, or
start in it, while tuples are removed or moved. When the primary bucket
page is not itself changed by the record, hashbucketcleanup(),
_hash_squeezebucket() and _hash_freeovflpage() got that lock by
registering the page with REGBUF_NO_CHANGE while holding only a pin on
it. That breaks the rule that a registered buffer is content-locked and
dirtied, and it is why wal_consistency_checking could compute the record
CRC over a page that a concurrent inserter was still changing (fixed on
its own in 27caf4ca5ae5 by not forcing an image for such a buffer).
Instead, store the primary bucket page's block number in the main data
of these three records, and have replay read that block and take the
cleanup lock on it directly, in the same order as before. The page is
no longer registered unless the record changes it. For the squeeze
record this also stops registering the write page when it is the
primary bucket page and is not modified.
With this, hash no longer uses REGBUF_NO_CHANGE.
The three record formats change, so bump XLOG_PAGE_MAGIC.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/hash/README | 9 ++++
src/backend/access/hash/hash.c | 15 +++----
src/backend/access/hash/hash_xlog.c | 56 ++++++++++++++++-------
src/backend/access/hash/hashovfl.c | 61 ++++++++------------------
src/backend/access/rmgrdesc/hashdesc.c | 9 ++--
src/include/access/hash_xlog.h | 18 ++++++--
src/include/access/xlog_internal.h | 2 +-
7 files changed, 93 insertions(+), 77 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..6d9b14e2d21 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record stores its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..fc93d78f6bb 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -902,6 +902,7 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
{
xl_hash_delete xlrec;
+ xlrec.bucket_blkno = bucket_blkno;
xlrec.clear_dead_marking = clear_dead_marking;
xlrec.is_primary_bucket_page = (buf == bucket_buf);
@@ -909,17 +910,11 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * If buf is an overflow page, the primary bucket page is not
+ * changed and we hold only a pin on it, so it is not
+ * registered. Replay takes a cleanup lock on bucket_blkno
+ * instead.
*/
- if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
-
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..04eb8e17dd4 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -469,6 +469,33 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on the primary bucket page of the bucket that a
+ * squeeze or delete record operates on, when that page is not one of the
+ * pages the record changes and so is not registered in it.
+ *
+ * This serializes replay against scans on a hot standby, which pin the
+ * primary bucket page for their whole duration; see the comments in the
+ * callers. The page is not modified, so nothing is done with it besides
+ * locking it. block_id must be a block of the same index registered in
+ * the record.
+ */
+static Buffer
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id,
+ BlockNumber bucket_blkno)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ Buffer buf;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -493,11 +520,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -617,14 +640,19 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ {
+ /* block 1 is absent if the primary bucket page is not modified */
+ if (XLogRecHasBlockRef(record, 1))
+ action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ action = BLK_NOTFOUND;
+ }
+ }
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -851,11 +879,7 @@ hash_xlog_delete(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..2bc9015c223 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -657,6 +657,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
{
xl_hash_squeeze_page xlrec;
+ xlrec.bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
xlrec.ntups = nitups;
@@ -667,42 +668,21 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Register only the pages this record changes. The primary bucket
+ * page is registered only if it is the write page and is modified;
+ * otherwise we may hold only a pin on it, and replay takes a cleanup
+ * lock on bucket_blkno instead.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
-
- if (nitups > 0)
+ if (mod_wbuf)
{
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
- {
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(1, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(1, itups[i], tups_size[i]);
+ }
}
XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
@@ -991,6 +971,7 @@ readpage:
{
xl_hash_move_page_contents xlrec;
+ xlrec.bucket_blkno = bucket_blkno;
xlrec.ntups = nitups;
xlrec.is_prim_bucket_same_wrt = (wbuf == bucket_buf);
@@ -998,17 +979,11 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Replay takes a cleanup
+ * lock on bucket_blkno instead.
*/
- if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
-
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
XLogRegisterBufData(1, itup_offsets,
nitups * sizeof(OffsetNumber));
diff --git a/src/backend/access/rmgrdesc/hashdesc.c b/src/backend/access/rmgrdesc/hashdesc.c
index 593013afe9c..6988b6a82c3 100644
--- a/src/backend/access/rmgrdesc/hashdesc.c
+++ b/src/backend/access/rmgrdesc/hashdesc.c
@@ -80,7 +80,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_move_page_contents *xlrec = (xl_hash_move_page_contents *) rec;
- appendStringInfo(buf, "ntups %d, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, ntups %d, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F');
break;
@@ -89,7 +90,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_squeeze_page *xlrec = (xl_hash_squeeze_page *) rec;
- appendStringInfo(buf, "prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
+ appendStringInfo(buf, "bucket_blkno %u, prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
+ xlrec->bucket_blkno,
xlrec->prevblkno,
xlrec->nextblkno,
xlrec->ntups,
@@ -101,7 +103,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_delete *xlrec = (xl_hash_delete *) rec;
- appendStringInfo(buf, "clear_dead_marking %c, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, clear_dead_marking %c, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->clear_dead_marking ? 'T' : 'F',
xlrec->is_primary_bucket_page ? 'T' : 'F');
break;
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..9d762ff70d3 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,12 +129,15 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page containing moved tuples
* Backup Blk 2: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered; replay takes a cleanup lock on
+ * bucket_blkno instead.
*/
typedef struct xl_hash_move_page_contents
{
+ BlockNumber bucket_blkno; /* primary bucket page */
uint16 ntups;
bool is_prim_bucket_same_wrt; /* true if the page to which
* tuples are moved is same as
@@ -149,16 +152,20 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
+ * Backup Blk 1: page containing tuples moved from freed overflow page, if
+ * it is modified
* Backup Blk 2: freed overflow page
* Backup Blk 3: page previous to the freed overflow page
* Backup Blk 4: page next to the freed overflow page
* Backup Blk 5: bitmap page containing info of freed overflow page
* Backup Blk 6: meta page
+ *
+ * The primary bucket page is registered only as block 1, when it is the
+ * modified write page; otherwise replay takes a cleanup lock on bucket_blkno.
*/
typedef struct xl_hash_squeeze_page
{
+ BlockNumber bucket_blkno; /* primary bucket page */
BlockNumber prevblkno;
BlockNumber nextblkno;
uint16 ntups;
@@ -179,11 +186,14 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page from which tuples are deleted
+ *
+ * If block 1 is not the primary bucket page, replay takes a cleanup lock on
+ * bucket_blkno, which is not registered.
*/
typedef struct xl_hash_delete
{
+ BlockNumber bucket_blkno; /* primary bucket page */
bool clear_dead_marking; /* true if this operation clears
* LH_PAGE_HAS_DEAD_TUPLES flag */
bool is_primary_bucket_page; /* true if the operation is for
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
--
2.54.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-10-31 11:32 ` Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
0 siblings, 1 reply; 34+ messages in thread
From: Amit Kapila @ 2026-10-31 11:32 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; +Cc: vignesh21@gmail.com; pgsql-hackers@lists.postgresql.org; michael@paquier.xyz; pgsql@j-davis.com; exclusion@gmail.com
On Fri, Oct 30, 2026 at 10:51 PM Greg Burd <greg@burd.me> wrote:
>
> On Fri, 30 Oct 2026 17:18:34 +0530, vignesh C <vignesh21@gmail.com> wrote:
>
> > The patches change the WAL records, and XLOG_PAGE_MAGIC cannot be
> > bumped in a minor release, so I looked at what happens if they are
> > backpatched. I built the base REL_18_STABLE, REL_18 + 0001, + 0002,
> > and + 0003 (attached, adapted for REL_18: the squeeze code there lacks
> > the locals present on master, so 0001 computes mod_wbuf itself) and
> > ran them against each other with streaming replication and crash
> > recovery, with wal_consistency_checking = 'hash' and VACUUM of hash
> > indexes in which every shape of the three records occurs.
>
> On your back-branch question: I don't think we should back-patch this.
>
+1. I also think this should be a master-only change helping us to
remove the use of REGBUF_NO_CHANGE from hash indexes. Also, the below
change to make it work on back-branches appears too hacky to me.
+#if HASH_WAL_REGISTER_BUCKET_PAGE
+ /* for standbys that predate the block number, see hash_xlog.h */
+ if (!xlrec.is_primary_bucket_page)
+ {
+ uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
+
+ XLogRegisterBuffer(0, bucket_buf, flags);
+ }
+#else
--
With Regards,
Amit Kapila.
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
@ 2026-11-03 16:11 ` Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 34+ messages in thread
From: Greg Burd @ 2026-11-03 16:11 UTC (permalink / raw)
To: pgsql-hackers; +Cc: amit.kapila16@gmail.com; greg@burd.me; vignesh21@gmail.com; pgsql-hackers@lists.postgresql.org; michael@paquier.xyz; pgsql@j-davis.com; exclusion@gmail.com
On Sat, 31 Oct 2026 17:02:34 +0530, Amit Kapila <amit.kapila16@gmail.com> wrote:
> +1. I also think this should be a master-only change helping us to
> remove the use of REGBUF_NO_CHANGE from hash indexes. Also, the below
> change to make it work on back-branches appears too hacky to me.
Thanks. Then the back branches stay on 27caf4ca5ae, and this series is
master only. The #if HASH_WAL_REGISTER_BUCKET_PAGE shim you quoted was
in Vignesh's REL_18 compatibility patch, and it is not part of this
series.
v4 is attached, rebased on current master (5681f0cfa5a). The only
change from v3 is formatting: pgperltidy rewraps a few lines in the new
TAP test. The C code is the same as in v3.
0001 Don't register pin-only primary bucket pages in hash WAL records
0002 Append the hash primary bucket block number to WAL records only
when needed (Vignesh; Amit's suggestion)
0003 Add a recovery test for the hash WAL pin-only bucket page fix
(co-authored with Vignesh)
0004 Remove REGBUF_NO_CHANGE
One point I'd like a reviewer to look at in 0001:
redo now reads a block the record does not register. The block number
is appended to the record's main data only when the primary bucket page
is not one of the pages the record changes. Redo takes the relation
from a block that is always registered (block 1 for DELETE and
MOVE_PAGE_CONTENTS, block 2 for SQUEEZE_PAGE), and reads the page with
RBM_NORMAL, so a missing page goes through the same invalid-page
tracking as when the page was registered.
The page is not modified, so it needs no full-page image and no LSN
update; the old code registered it with REGBUF_NO_IMAGE, so redo already
worked from the on-disk copy. Two consumers of block references stop
seeing it. Recovery prefetch is one, so redo may do one synchronous
read of the bucket page per record when the page isn't cached. The
other is tools that collect changed blocks from WAL, such as pg_rewind
and the WAL summarizer, and losing it there is harmless because the page
is not changed. FSM redo reads unregistered blocks the same way, and
nbtree's pin scan did until 9f83468b353.
Testing:
- meson test setup, regress, isolation, recovery, pg_waldump and the
hash module, with PG_TEST_EXTRA=wal_consistency_checking, all four
patches applied: 68 of 68 suites pass on both builds, including
061_hash_vacuum_insert_crc and 027_stream_regress. With 0001 applied
alone, the same suites minus isolation also pass (64 of 64), so 0001
can be committed on its own.
- Streaming-standby CRC reproducer: 8 sessions inserting and deleting on
a single-bucket index under aggressive autovacuum,
wal_consistency_checking = 'hash'. As a control I ran master with
27caf4ca5ae reverted: the standby stops on "incorrect resource manager
data checksum". With v4, which also has 0004's REGBUF_NO_CHANGE
removal and restored asserts, the standby caught up with no errors.
- Cleanup lock on the standby: a cursor is parked in the bucket's
overflow chain, then the primary vacuums so that every DELETE,
MOVE_PAGE_CONTENTS and SQUEEZE_PAGE record has the primary bucket page
unmodified (is_primary F). On both builds replay waits on
BufferCleanup until the cursor finishes, and the cursor sees all 2250
rows, the same as unpatched master.
- I also reran the deadlock check from my first message on this thread
against current master. Taking the primary bucket page lock in
_hash_freeovflpage() after the metapage is locked exclusive still
hangs VACUUM and a scan of a bucket being populated by an incomplete
split. Taking it before the metapage read does not. 0001 takes
neither lock; this is only why the series doesn't lock the page.
I think 0001-0003 are ready for a committer. 0004 can go in with them
or right after.
best.
-greg
Attachments: download all (4 files, .tar.gz)
v4-0001-Don-t-register-pin-only-primary-bucket-pages-in-h.patch (text/plain, 15.4K) download
From 735170984e0d69ab879b4042e695d1eb3d1ebd6e Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v4 1/4] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the bucket's primary
page, so that a hot standby scan cannot be in progress in the bucket, or
start in it, while tuples are removed or moved. When the primary bucket
page is not itself changed by the record, hashbucketcleanup(),
_hash_squeezebucket() and _hash_freeovflpage() got that lock by
registering the page with REGBUF_NO_CHANGE while holding only a pin on
it. That breaks the rule that a registered buffer is content-locked and
dirtied, and it is why wal_consistency_checking could compute the record
CRC over a page that a concurrent inserter was still changing (fixed on
its own in 27caf4ca5ae5 by not forcing an image for such a buffer).
Instead, store the primary bucket page's block number in the main data
of these three records, and have replay read that block and take the
cleanup lock on it directly, in the same order as before. The page is
no longer registered unless the record changes it. For the squeeze
record this also stops registering the write page when it is the
primary bucket page and is not modified.
With this, hash no longer uses REGBUF_NO_CHANGE.
The three record formats change, so bump XLOG_PAGE_MAGIC.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/hash/README | 9 ++++
src/backend/access/hash/hash.c | 15 +++----
src/backend/access/hash/hash_xlog.c | 56 ++++++++++++++++-------
src/backend/access/hash/hashovfl.c | 61 ++++++++------------------
src/backend/access/rmgrdesc/hashdesc.c | 9 ++--
src/include/access/hash_xlog.h | 18 ++++++--
src/include/access/xlog_internal.h | 2 +-
7 files changed, 93 insertions(+), 77 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..6d9b14e2d21 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record stores its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..fc93d78f6bb 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -902,6 +902,7 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
{
xl_hash_delete xlrec;
+ xlrec.bucket_blkno = bucket_blkno;
xlrec.clear_dead_marking = clear_dead_marking;
xlrec.is_primary_bucket_page = (buf == bucket_buf);
@@ -909,17 +910,11 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * If buf is an overflow page, the primary bucket page is not
+ * changed and we hold only a pin on it, so it is not
+ * registered. Replay takes a cleanup lock on bucket_blkno
+ * instead.
*/
- if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
-
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..04eb8e17dd4 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -469,6 +469,33 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on the primary bucket page of the bucket that a
+ * squeeze or delete record operates on, when that page is not one of the
+ * pages the record changes and so is not registered in it.
+ *
+ * This serializes replay against scans on a hot standby, which pin the
+ * primary bucket page for their whole duration; see the comments in the
+ * callers. The page is not modified, so nothing is done with it besides
+ * locking it. block_id must be a block of the same index registered in
+ * the record.
+ */
+static Buffer
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id,
+ BlockNumber bucket_blkno)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ Buffer buf;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -493,11 +520,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -617,14 +640,19 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ {
+ /* block 1 is absent if the primary bucket page is not modified */
+ if (XLogRecHasBlockRef(record, 1))
+ action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ action = BLK_NOTFOUND;
+ }
+ }
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -851,11 +879,7 @@ hash_xlog_delete(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..2bc9015c223 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -657,6 +657,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
{
xl_hash_squeeze_page xlrec;
+ xlrec.bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
xlrec.ntups = nitups;
@@ -667,42 +668,21 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Register only the pages this record changes. The primary bucket
+ * page is registered only if it is the write page and is modified;
+ * otherwise we may hold only a pin on it, and replay takes a cleanup
+ * lock on bucket_blkno instead.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
-
- if (nitups > 0)
+ if (mod_wbuf)
{
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
- {
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(1, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(1, itups[i], tups_size[i]);
+ }
}
XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
@@ -991,6 +971,7 @@ readpage:
{
xl_hash_move_page_contents xlrec;
+ xlrec.bucket_blkno = bucket_blkno;
xlrec.ntups = nitups;
xlrec.is_prim_bucket_same_wrt = (wbuf == bucket_buf);
@@ -998,17 +979,11 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Replay takes a cleanup
+ * lock on bucket_blkno instead.
*/
- if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
-
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
XLogRegisterBufData(1, itup_offsets,
nitups * sizeof(OffsetNumber));
diff --git a/src/backend/access/rmgrdesc/hashdesc.c b/src/backend/access/rmgrdesc/hashdesc.c
index 593013afe9c..6988b6a82c3 100644
--- a/src/backend/access/rmgrdesc/hashdesc.c
+++ b/src/backend/access/rmgrdesc/hashdesc.c
@@ -80,7 +80,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_move_page_contents *xlrec = (xl_hash_move_page_contents *) rec;
- appendStringInfo(buf, "ntups %d, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, ntups %d, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F');
break;
@@ -89,7 +90,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_squeeze_page *xlrec = (xl_hash_squeeze_page *) rec;
- appendStringInfo(buf, "prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
+ appendStringInfo(buf, "bucket_blkno %u, prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
+ xlrec->bucket_blkno,
xlrec->prevblkno,
xlrec->nextblkno,
xlrec->ntups,
@@ -101,7 +103,8 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_delete *xlrec = (xl_hash_delete *) rec;
- appendStringInfo(buf, "clear_dead_marking %c, is_primary %c",
+ appendStringInfo(buf, "bucket_blkno %u, clear_dead_marking %c, is_primary %c",
+ xlrec->bucket_blkno,
xlrec->clear_dead_marking ? 'T' : 'F',
xlrec->is_primary_bucket_page ? 'T' : 'F');
break;
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..9d762ff70d3 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,12 +129,15 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page containing moved tuples
* Backup Blk 2: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered; replay takes a cleanup lock on
+ * bucket_blkno instead.
*/
typedef struct xl_hash_move_page_contents
{
+ BlockNumber bucket_blkno; /* primary bucket page */
uint16 ntups;
bool is_prim_bucket_same_wrt; /* true if the page to which
* tuples are moved is same as
@@ -149,16 +152,20 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
+ * Backup Blk 1: page containing tuples moved from freed overflow page, if
+ * it is modified
* Backup Blk 2: freed overflow page
* Backup Blk 3: page previous to the freed overflow page
* Backup Blk 4: page next to the freed overflow page
* Backup Blk 5: bitmap page containing info of freed overflow page
* Backup Blk 6: meta page
+ *
+ * The primary bucket page is registered only as block 1, when it is the
+ * modified write page; otherwise replay takes a cleanup lock on bucket_blkno.
*/
typedef struct xl_hash_squeeze_page
{
+ BlockNumber bucket_blkno; /* primary bucket page */
BlockNumber prevblkno;
BlockNumber nextblkno;
uint16 ntups;
@@ -179,11 +186,14 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page from which tuples are deleted
+ *
+ * If block 1 is not the primary bucket page, replay takes a cleanup lock on
+ * bucket_blkno, which is not registered.
*/
typedef struct xl_hash_delete
{
+ BlockNumber bucket_blkno; /* primary bucket page */
bool clear_dead_marking; /* true if this operation clears
* LH_PAGE_HAS_DEAD_TUPLES flag */
bool is_primary_bucket_page; /* true if the operation is for
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
--
2.50.1
v4-0004-Remove-REGBUF_NO_CHANGE.patch (text/plain, 5.2K) download
From 02a691127756c5b24b53cea20aa90e8839d8f397 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:17:46 -0400
Subject: [PATCH v4 4/4] Remove REGBUF_NO_CHANGE
With the previous commits, the hash index AM no longer registers any
pin-only or otherwise-unchanged buffer, so REGBUF_NO_CHANGE has no users
left. Remove the flag and restore the invariant that every registered
buffer is content-locked and dirty: XLogRegisterBuffer() asserts it
unconditionally again.
This also reverts the defensive measures added in 27caf4ca5ae5, which
let a REGBUF_NO_CHANGE buffer skip the full-page image forced by
wal_consistency_checking: XLogRecordAssemble() no longer special-cases
the flag, and verifyBackupPageConsistency() again asserts that a
registered block carries an image. 27caf4ca5ae5 remains in the back
branches, where this hash rework is not applied.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/transam/README | 5 ----
src/backend/access/transam/xloginsert.c | 28 ++++++-----------------
src/backend/access/transam/xlogrecovery.c | 7 +-----
src/include/access/xloginsert.h | 3 ---
4 files changed, 8 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/transam/README b/src/backend/access/transam/README
index 595afa01fa7..231106270fd 100644
--- a/src/backend/access/transam/README
+++ b/src/backend/access/transam/README
@@ -586,11 +586,6 @@ void XLogRegisterBuffer(uint8 block_id, Buffer buf, uint8 flags);
XLogRegisterBufData() is included in the WAL record even if a full-page
image is taken.
- The REGBUF_NO_CHANGE flag indicates that the buffer is registered without
- being modified by this record, and possibly without an exclusive content
- lock. wal_consistency_checking does not force a full-page image for such
- a buffer.
-
void XLogRegisterData(const void *data, int len);
XLogRegisterData is used to include arbitrary data in the WAL record. If
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index cd3359434e1..2d031e38594 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -257,22 +257,13 @@ XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Assert(begininsert_called);
/*
- * Ordinarily, the buffer should be exclusive-locked (or share-exclusive
- * in case of hint bits) and marked dirty before we get here, otherwise we
- * could end up violating one of the rules in access/transam/README.
- *
- * Some callers intentionally register a clean page and never update that
- * page's LSN; in that case they can pass the flag REGBUF_NO_CHANGE to
- * bypass these checks.
+ * The buffer should be exclusive-locked (or share-exclusive in case of
+ * hint bits) and marked dirty before we get here, otherwise we could end
+ * up violating one of the rules in access/transam/README.
*/
-#ifdef USE_ASSERT_CHECKING
- if (!(flags & REGBUF_NO_CHANGE))
- {
- Assert(BufferIsDirty(buffer));
- Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
- BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
- }
-#endif
+ Assert(BufferIsDirty(buffer));
+ Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
+ BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
if (block_id >= max_registered_block_id)
{
@@ -722,13 +713,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
- *
- * Do not force an image for a REGBUF_NO_CHANGE buffer.
*/
- if (regbuf->flags & REGBUF_NO_CHANGE)
- include_image = needs_backup;
- else
- include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
+ include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..7a1de0567a8 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2488,12 +2488,7 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- /*
- * Blocks registered with REGBUF_NO_CHANGE may have no image, see
- * XLogRecordAssemble(). Nothing to compare for these.
- */
- if (!XLogRecHasBlockImage(record, block_id))
- continue;
+ Assert(XLogRecHasBlockImage(record, block_id));
if (XLogRecBlockImageApply(record, block_id))
{
diff --git a/src/include/access/xloginsert.h b/src/include/access/xloginsert.h
index 86264564ebb..ddb1a85db59 100644
--- a/src/include/access/xloginsert.h
+++ b/src/include/access/xloginsert.h
@@ -38,9 +38,6 @@
* will be skipped) */
#define REGBUF_KEEP_DATA 0x10 /* include data even if a full-page image
* is taken */
-#define REGBUF_NO_CHANGE 0x20 /* intentionally register clean buffer; no
- * image is forced for WAL consistency
- * checking */
/* prototypes for public functions in xloginsert.c: */
extern void XLogBeginInsert(void);
--
2.50.1
v4-0003-Add-a-recovery-test-for-the-hash-WAL-pin-only-buc.patch (text/plain, 11.4K) download
From 358e876f2961d926fe93e5a5c445b8a357a24306 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v4 3/4] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/061_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 +++
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_vacuum_insert_crc.pl | 181 ++++++++++++++++++
3 files changed, 204 insertions(+)
create mode 100644 src/test/recovery/t/061_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..5051031df56 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_vacuum_insert_crc.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_vacuum_insert_crc.pl b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..aa030abd587
--- /dev/null
+++ b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
@@ -0,0 +1,181 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.50.1
v4-0002-Append-the-hash-primary-bucket-block-number-to-WA.patch (text/plain, 13.3K) download
From a1221c88a3f8916321c68c8230a5009f9c4527de Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 09:13:23 -0400
Subject: [PATCH v4 2/4] Append the hash primary bucket block number to WAL
records only when needed
The previous commit stores the primary bucket page's block number in
xl_hash_delete, xl_hash_move_page_contents and xl_hash_squeeze_page.
Replay only uses it when the primary bucket page is not one of the pages
the record changes, so in the other cases the four bytes are wasted.
Remove the field from the three structs, and append the block number to
the main data of the record only when the primary bucket page is not
registered or modified by it. Replay reads it from just after the
fixed-size struct. The structs return to their previous sizes, and the
records are no larger than before in the common case.
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Author: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm2L_0eJ1yKbp4OM9XdyrGHpyK3iU49nbc5hCRe3F+MPjg@mail.gmail.com
---
src/backend/access/hash/README | 2 +-
src/backend/access/hash/hash.c | 8 ++++---
src/backend/access/hash/hash_xlog.c | 19 ++++++++++------
src/backend/access/hash/hashovfl.c | 31 +++++++++++++++++---------
src/backend/access/rmgrdesc/hashdesc.c | 9 +++-----
src/include/access/hash_xlog.h | 19 +++++++++-------
6 files changed, 53 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index 6d9b14e2d21..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -647,7 +647,7 @@ that no scan on a hot standby is in progress in the bucket or can start in
it while tuples are removed or moved; such a scan could otherwise miss
tuples or return them twice. When the primary bucket page is not one of
the pages the record changes, the operation holds only a pin on it, so it
-is not registered in the record. The record stores its block number
+is not registered in the record. The record then carries its block number
instead, and replay locks that block directly.
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index fc93d78f6bb..9dbd008fed9 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -902,7 +902,6 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
{
xl_hash_delete xlrec;
- xlrec.bucket_blkno = bucket_blkno;
xlrec.clear_dead_marking = clear_dead_marking;
xlrec.is_primary_bucket_page = (buf == bucket_buf);
@@ -912,9 +911,12 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
/*
* If buf is an overflow page, the primary bucket page is not
* changed and we hold only a pin on it, so it is not
- * registered. Replay takes a cleanup lock on bucket_blkno
- * instead.
+ * registered. Append its block number instead, and replay
+ * takes a cleanup lock on it. It is not needed otherwise.
*/
+ if (!xlrec.is_primary_bucket_page)
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 04eb8e17dd4..1484c12d948 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -472,7 +472,9 @@ hash_xlog_split_complete(XLogReaderState *record)
/*
* Take a cleanup lock on the primary bucket page of the bucket that a
* squeeze or delete record operates on, when that page is not one of the
- * pages the record changes and so is not registered in it.
+ * pages the record changes and so is not registered in it. Its block number
+ * is stored in the main data of the record, right after the fixed-size struct
+ * of rec_size bytes.
*
* This serializes replay against scans on a hot standby, which pin the
* primary bucket page for their whole duration; see the comments in the
@@ -481,13 +483,16 @@ hash_xlog_split_complete(XLogReaderState *record)
* the record.
*/
static Buffer
-hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id,
- BlockNumber bucket_blkno)
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
{
RelFileLocator rlocator;
ForkNumber forknum;
+ BlockNumber bucket_blkno;
Buffer buf;
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
RBM_NORMAL, InvalidBuffer);
@@ -520,7 +525,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashMovePageContents);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -646,13 +651,13 @@ hash_xlog_squeeze_page(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, SizeOfHashSqueezePage);
action = BLK_NOTFOUND;
}
}
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 2, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 2, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -879,7 +884,7 @@ hash_xlog_delete(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
else
{
- bucketbuf = hash_xlog_lock_bucket(record, 1, xldata->bucket_blkno);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashDelete);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index 2bc9015c223..91781f7c2b0 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,8 +660,8 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
- xlrec.bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
xlrec.ntups = nitups;
@@ -670,9 +674,12 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/*
* Register only the pages this record changes. The primary bucket
* page is registered only if it is the write page and is modified;
- * otherwise we may hold only a pin on it, and replay takes a cleanup
- * lock on bucket_blkno instead.
+ * otherwise we may hold only a pin on it, so append its block number
+ * and replay takes a cleanup lock on it.
*/
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
if (mod_wbuf)
{
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
@@ -946,10 +953,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -971,7 +980,6 @@ readpage:
{
xl_hash_move_page_contents xlrec;
- xlrec.bucket_blkno = bucket_blkno;
xlrec.ntups = nitups;
xlrec.is_prim_bucket_same_wrt = (wbuf == bucket_buf);
@@ -981,9 +989,12 @@ readpage:
/*
* If wbuf is an overflow page, the primary bucket
* page is not changed and we hold only a pin on it,
- * so it is not registered. Replay takes a cleanup
- * lock on bucket_blkno instead.
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
+ if (!xlrec.is_prim_bucket_same_wrt)
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
+
XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
XLogRegisterBufData(1, itup_offsets,
nitups * sizeof(OffsetNumber));
diff --git a/src/backend/access/rmgrdesc/hashdesc.c b/src/backend/access/rmgrdesc/hashdesc.c
index 6988b6a82c3..593013afe9c 100644
--- a/src/backend/access/rmgrdesc/hashdesc.c
+++ b/src/backend/access/rmgrdesc/hashdesc.c
@@ -80,8 +80,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_move_page_contents *xlrec = (xl_hash_move_page_contents *) rec;
- appendStringInfo(buf, "bucket_blkno %u, ntups %d, is_primary %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "ntups %d, is_primary %c",
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F');
break;
@@ -90,8 +89,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_squeeze_page *xlrec = (xl_hash_squeeze_page *) rec;
- appendStringInfo(buf, "bucket_blkno %u, prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "prevblkno %u, nextblkno %u, ntups %d, is_primary %c, is_previous %c",
xlrec->prevblkno,
xlrec->nextblkno,
xlrec->ntups,
@@ -103,8 +101,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
{
xl_hash_delete *xlrec = (xl_hash_delete *) rec;
- appendStringInfo(buf, "bucket_blkno %u, clear_dead_marking %c, is_primary %c",
- xlrec->bucket_blkno,
+ appendStringInfo(buf, "clear_dead_marking %c, is_primary %c",
xlrec->clear_dead_marking ? 'T' : 'F',
xlrec->is_primary_bucket_page ? 'T' : 'F');
break;
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 9d762ff70d3..12fc5f50ea5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -132,12 +132,13 @@ typedef struct xl_hash_split_complete
* Backup Blk 1: page containing moved tuples
* Backup Blk 2: page from which tuples will be removed
*
- * The primary bucket page is not registered; replay takes a cleanup lock on
- * bucket_blkno instead.
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
- BlockNumber bucket_blkno; /* primary bucket page */
uint16 ntups;
bool is_prim_bucket_same_wrt; /* true if the page to which
* tuples are moved is same as
@@ -161,11 +162,12 @@ typedef struct xl_hash_move_page_contents
* Backup Blk 6: meta page
*
* The primary bucket page is registered only as block 1, when it is the
- * modified write page; otherwise replay takes a cleanup lock on bucket_blkno.
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
- BlockNumber bucket_blkno; /* primary bucket page */
BlockNumber prevblkno;
BlockNumber nextblkno;
uint16 ntups;
@@ -188,12 +190,13 @@ typedef struct xl_hash_squeeze_page
*
* Backup Blk 1: page from which tuples are deleted
*
- * If block 1 is not the primary bucket page, replay takes a cleanup lock on
- * bucket_blkno, which is not registered.
+ * If block 1 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
- BlockNumber bucket_blkno; /* primary bucket page */
bool clear_dead_marking; /* true if this operation clears
* LH_PAGE_HAS_DEAD_TUPLES flag */
bool is_primary_bucket_page; /* true if the operation is for
--
2.50.1
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-06 10:44 ` Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
0 siblings, 1 reply; 34+ messages in thread
From: Amit Kapila @ 2026-11-06 10:44 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; +Cc: pgsql-hackers; vignesh21@gmail.com; pgsql-hackers@lists.postgresql.org; michael@paquier.xyz; pgsql@j-davis.com; exclusion@gmail.com
On Tue, Nov 3, 2026 at 9:41 PM Greg Burd <greg@burd.me> wrote:
>
> On Sat, 31 Oct 2026 17:02:34 +0530, Amit Kapila <amit.kapila16@gmail.com> wrote:
> > +1. I also think this should be a master-only change helping us to
> > remove the use of REGBUF_NO_CHANGE from hash indexes. Also, the below
> > change to make it work on back-branches appears too hacky to me.
>
> Thanks. Then the back branches stay on 27caf4ca5ae, and this series is
> master only. The #if HASH_WAL_REGISTER_BUCKET_PAGE shim you quoted was
> in Vignesh's REL_18 compatibility patch, and it is not part of this
> series.
>
> v4 is attached, rebased on current master (5681f0cfa5a). The only
> change from v3 is formatting: pgperltidy rewraps a few lines in the new
> TAP test. The C code is the same as in v3.
>
> 0001 Don't register pin-only primary bucket pages in hash WAL records
> 0002 Append the hash primary bucket block number to WAL records only
> when needed (Vignesh; Amit's suggestion)
I think we can merge 0001 and 0002 now. I don't see the need for
additional four bytes in common cases for each WAL record we modify as
part of this patch.
One additional comment:
*
- * Backup Blk 0: primary bucket page
* Backup Blk 1: page from which tuples are deleted
+ *
+ * If block 1 is not the primary bucket page, replay takes a cleanup lock on
+ * bucket_blkno, which is not registered.
*/
typedef struct xl_hash_delete
{
+ BlockNumber bucket_blkno; /* primary bucket page */
After this change, shouldn't Backup Blk 1 be numbered as 0? Because
now 0 doesn't have anything. The same is true for other records that
are modified.
--
With Regards,
Amit Kapila.
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
@ 2026-11-11 03:03 ` shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
0 siblings, 1 reply; 34+ messages in thread
From: shihao zhong @ 2026-11-11 03:03 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Greg Burd <greg@burd.me>; pgsql-hackers; vignesh21@gmail.com; pgsql-hackers@lists.postgresql.org; michael@paquier.xyz; pgsql@j-davis.com; exclusion@gmail.com
Hi Greg,
> One point I'd like a reviewer to look at in 0001:
>
> redo now reads a block the record does not register.
Could that be a torn page?
> The page is not modified, so it needs no full-page image and no LSN
> update; the old code registered it with REGBUF_NO_IMAGE, so redo already
> worked from the on-disk copy.
I think if we have a torn bucket page and an XLOG_HASH_DELETE for one
of its overflow pages before the FPI, we may hit an issue?
We do not register an FPI for it in hashbucketcleanup().
if (!xlrec.is_primary_bucket_page)
{
uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE |
REGBUF_NO_CHANGE;
XLogRegisterBuffer(0, bucket_buf, flags);
}
XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
Then hash_xlog_delete() reads it from disk in the else branch, and
that read fails.
if (xldata->is_primary_bucket_page)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL,
true, &deletebuf);
else
{
(void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL,
true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
I don't think this is caused by your patch. This looks like an
existing bug in master.
I am afraid that adding an FPI will not work either, because VACUUM
only holds a pin on the page and not an exclusive lock. But getting an
exclusive lock may hit the deadlock you mentioned. Maybe the right way
is to fix it on the replay side?
Thanks,
Shihao
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
@ 2026-11-11 09:28 ` vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 34+ messages in thread
From: vignesh C @ 2026-11-11 09:28 UTC (permalink / raw)
To: shihao zhong <zhong950419@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; Greg Burd <greg@burd.me>; pgsql-hackers; pgsql-hackers@lists.postgresql.org; michael@paquier.xyz; pgsql@j-davis.com; exclusion@gmail.com
On Wed, 11 Nov 2026 at 08:33, shihao zhong <zhong950419@gmail.com> wrote:
>
> Hi Greg,
>
> > One point I'd like a reviewer to look at in 0001:
> >
> > redo now reads a block the record does not register.
>
> Could that be a torn page?
>
> > The page is not modified, so it needs no full-page image and no LSN
> > update; the old code registered it with REGBUF_NO_IMAGE, so redo already
> > worked from the on-disk copy.
>
> I think if we have a torn bucket page and an XLOG_HASH_DELETE for one
> of its overflow pages before the FPI, we may hit an issue?
>
> We do not register an FPI for it in hashbucketcleanup().
>
> if (!xlrec.is_primary_bucket_page)
> {
> uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE |
> REGBUF_NO_CHANGE;
>
> XLogRegisterBuffer(0, bucket_buf, flags);
> }
>
> XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
>
> Then hash_xlog_delete() reads it from disk in the else branch, and
> that read fails.
>
> if (xldata->is_primary_bucket_page)
> action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL,
> true, &deletebuf);
> else
> {
> (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL,
> true, &bucketbuf);
>
> action = XLogReadBufferForRedo(record, 1, &deletebuf);
> }
>
> I don't think this is caused by your patch. This looks like an
> existing bug in master.
Thanks for the report. I was able to reproduce this on HEAD.
The attached test
(src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl) does
the following, with data checksums enabled: a) Builds a hash index
with all keys in one bucket, consisting of a primary page P and an
overflow page, and takes a checkpoint. b) Runs VACUUM to remove dead
entries from the overflow page only. This writes an XLOG_HASH_DELETE
record for the overflow page without modifying P. c) Runs a second
VACUUM to remove dead entries from P. This is the first modification
to P since the checkpoint, so the corresponding WAL record includes a
full-page image (FPI) of P. d) Crashes the server, overwrites the
second half of P in the data file with random bytes to simulate a torn
write, and restarts the server.
Crash recovery then fails while replaying the first record (the DELETE
for the overflow page), before reaching the record containing the FPI
of P:
FATAL: invalid page in block 7 of relation "base/5/16387"
CONTEXT: WAL redo at 0/017745E0 for Hash/DELETE: ... is_primary F;
blkref #1: ... blk 10 FPW
During redo, we read P only to acquire the cleanup lock, using
RBM_NORMAL. The read therefore fails checksum verification. The test
fails in the same way without the patch, where P is accessed through
block 0, and with the patch, where it is accessed through
bucket_blkno.
Since we only need P to acquire the cleanup lock and don't actually
need its contents, I think we should read it using RBM_ZERO_ON_ERROR
in hash_xlog_lock_bucket(). This would zero the buffer instead of
raising an error when a torn page is encountered, allowing the FPI
later in the WAL to restore the correct contents.
Do you think RBM_ZERO_ON_ERROR is the right approach here, or is there
a better solution to fix this?
Regards,
Vignesh
Attachments:
068a_hash_torn_primary_page_delete_first.pl (text/x-perl-script, 4.0K) download
# Copyright (c) 2026, PostgreSQL Global Development Group
# Test crash recovery when the primary bucket page of a hash bucket is torn,
# and the full-page image that repairs it comes after the record that reads it.
#
use strict;
use warnings FATAL => 'all';
use IPC::Run;
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;
my $node = PostgreSQL::Test::Cluster->new('primary');
$node->init;
$node->append_conf(
'postgresql.conf', qq{
autovacuum = off
fsync = off
full_page_writes = on
checkpoint_timeout = 1h
});
$node->start;
is($node->safe_psql('postgres', 'SHOW data_checksums'),
'on', 'premise: data checksums are on');
# One bucket receives every key: a primary page holding about 407 entries and
# an overflow page with the rest.
$node->safe_psql(
'postgres', q{
CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
CREATE INDEX t_i ON t USING hash (k);
INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
});
$node->safe_psql('postgres', 'CHECKPOINT');
my $redo = $node->safe_psql('postgres',
'SELECT redo_lsn FROM pg_control_checkpoint()');
# The entries of ids 451-600 are on the overflow page, those of ids 1-50 on the
# primary page. The DELETE for the overflow page comes first; the VACUUM of
# the primary page then changes it for the first time since the checkpoint, so
# its record carries the full-page image of the page.
$node->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
$node->safe_psql('postgres', 'VACUUM t');
$node->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
$node->safe_psql('postgres', 'VACUUM t');
my $relpath = $node->safe_psql('postgres',
q{SELECT pg_relation_filepath('t_i')});
my $bs = $node->safe_psql('postgres', 'SHOW block_size');
$node->safe_psql('postgres', 'SELECT pg_switch_wal()');
# Read the Hash records after the checkpoint.
my ($stdout, $stderr);
IPC::Run::run(
[
'pg_waldump',
'--path' => $node->data_dir . '/pg_wal',
'--start' => $redo,
'--rmgr' => 'Hash',
],
'>' => \$stdout,
'2>' => \$stderr);
my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
# The primary page: named by the first DELETE for an overflow page.
my ($idx_delete) =
grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
ok(defined $idx_delete,
'premise: VACUUM wrote a DELETE for an overflow page')
or diag $stdout;
my $pblk;
if (defined $idx_delete)
{
($pblk) = $records[$idx_delete] =~ /bucket_blkno (\d+)/;
($pblk) = $records[$idx_delete] =~ /blkref #0: rel \S+ blk (\d+)/
unless defined $pblk;
}
ok(defined $pblk, 'premise: found the primary bucket page')
or diag $stdout;
# Where the first full-page image of the primary page is, relative to the
# DELETE for the overflow page.
my ($idx_fpi) =
defined $pblk
? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
0 .. $#records
: ();
ok(defined $idx_fpi,
'premise: the primary page got a full-page image after the checkpoint')
or diag $stdout;
if (defined $idx_delete && defined $idx_fpi)
{
cmp_ok($idx_delete, '<', $idx_fpi,
'premise: the DELETE comes before the image of the primary page');
}
$node->stop('immediate');
# Simulate a torn write of the primary page: keep the first half of its block
# and overwrite the second half.
if (defined $pblk)
{
my $path = $node->data_dir . '/' . $relpath;
open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
syswrite($fh, $junk) == $bs / 2 or die "write: $!";
close($fh);
}
my $started = $node->start(fail_ok => 1);
ok($started, 'crash recovery succeeds');
if ($started)
{
is( $node->safe_psql(
'postgres',
q{SET enable_seqscan = off; SET enable_bitmapscan = off;
SELECT count(*) FROM t WHERE k = 1}),
'400',
'the hash index gives the right result after recovery');
$node->stop;
}
else
{
my $log = slurp_file($node->logfile);
diag("the server did not start; the log has:\n"
. join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
}
done_testing();
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
@ 2026-11-11 11:49 ` Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 18:14 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
0 siblings, 2 replies; 34+ messages in thread
From: Amit Kapila @ 2026-11-11 11:49 UTC (permalink / raw)
To: vignesh C <vignesh21@gmail.com>; +Cc: shihao zhong <zhong950419@gmail.com>; Greg Burd <greg@burd.me>; pgsql-hackers; pgsql-hackers@lists.postgresql.org; michael@paquier.xyz; pgsql@j-davis.com; exclusion@gmail.com
On Wed, Nov 11, 2026 at 2:59 PM vignesh C <vignesh21@gmail.com> wrote:
>
> On Wed, 11 Nov 2026 at 08:33, shihao zhong <zhong950419@gmail.com> wrote:
> >
>
> Thanks for the report. I was able to reproduce this on HEAD.
> The attached test
> (src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl) does
> the following, with data checksums enabled: a) Builds a hash index
> with all keys in one bucket, consisting of a primary page P and an
> overflow page, and takes a checkpoint. b) Runs VACUUM to remove dead
> entries from the overflow page only. This writes an XLOG_HASH_DELETE
> record for the overflow page without modifying P. c) Runs a second
> VACUUM to remove dead entries from P. This is the first modification
> to P since the checkpoint, so the corresponding WAL record includes a
> full-page image (FPI) of P. d) Crashes the server, overwrites the
> second half of P in the data file with random bytes to simulate a torn
> write, and restarts the server.
>
> Crash recovery then fails while replaying the first record (the DELETE
> for the overflow page), before reaching the record containing the FPI
> of P:
> FATAL: invalid page in block 7 of relation "base/5/16387"
> CONTEXT: WAL redo at 0/017745E0 for Hash/DELETE: ... is_primary F;
> blkref #1: ... blk 10 FPW
>
> During redo, we read P only to acquire the cleanup lock, using
> RBM_NORMAL. The read therefore fails checksum verification. The test
> fails in the same way without the patch, where P is accessed through
> block 0, and with the patch, where it is accessed through
> bucket_blkno.
> Since we only need P to acquire the cleanup lock and don't actually
> need its contents, I think we should read it using RBM_ZERO_ON_ERROR
> in hash_xlog_lock_bucket(). This would zero the buffer instead of
> raising an error when a torn page is encountered, allowing the FPI
> later in the WAL to restore the correct contents.
>
> Do you think RBM_ZERO_ON_ERROR is the right approach here, or is there
> a better solution to fix this?
>
The code comments related to RBM_ZERO_ON_ERROR states following:
"RBM_ZERO_ON_ERROR is like the normal mode, but if the page header is
not
valid, the page is zeroed instead of throwing an error. This is
intended for non-critical data, where the caller is prepared to repair
errors.". And, I see RBM_ZERO_ON_ERROR mode is only used for VM and
FSM pages which don't contain user-data. So, it doesn't sound like a
good idea to use RBM_ZERO_ON_ERROR.
Can we explore guarding the read/lock of bucket_page during replay by
HotStandbyActiveInReplay()? IIRC, the cleanup lock is required during
replay to prevent concurrent scans from reading incorrect data. So,
once the consistency is reached, we should be okay to read/lock the
primary page.
I feel we should also explore the idea of locking the bucket page even
when we are registering without it being changed to avoid this
problem. I'll also think about it.
--
With Regards,
Amit Kapila.
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
@ 2026-11-11 18:14 ` Greg Burd <greg@burd.me>
1 sibling, 0 replies; 34+ messages in thread
From: Greg Burd @ 2026-11-11 18:14 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: shihao zhong <zhong950419@gmail.com>; vignesh C <vignesh21@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
Hello,
Thanks Amit for the review, and thanks Shihao for finding the torn-page
case.
Per Amit's suggestion I merged the old 0001 and 0002 into a single
patch. The primary bucket block number is now appended to the record
only when the primary bucket page is not one of the pages the record
changes, so there is no common-case size increase at any point in the
series. The structs never carry the block number.
I also renumbered the registered blocks as Amit noted. Since the
primary bucket page is no longer registered as block 0 in DELETE,
MOVE_PAGE_CONTENTS or SQUEEZE_PAGE, I shifted the remaining blocks down
by one, so each record's registered blocks start at 0 again:
DELETE block 0: page tuples are deleted from
MOVE_PAGE_CONTENTS block 0: page tuples are moved to
block 1: page tuples are moved from
SQUEEZE_PAGE block 0: write page (if modified)
block 1: freed overflow page
block 2: page before the freed overflow page
block 3: page after the freed overflow page
block 4: bitmap page
block 5: meta page
The record descriptions in hash_xlog.h are updated to match, and the
recovery test still selects the overflow-page DELETE by its main-data
length, which does not change.
0001 Don't register pin-only primary bucket pages in hash WAL records
(now includes the append-only-when-needed change; Vignesh,
Amit's suggestion)
0002 Add a recovery test for the hash WAL pin-only bucket page fix
(co-authored with Vignesh)
0003 Remove REGBUF_NO_CHANGE
The case of the torn-page
I reproduced and traced Shihao's case and I agree it is a real,
pre-existing bug on master, not something this series introduces. The
sequence is: with data checksums on, a VACUUM writes an XLOG_HASH_DELETE
for an overflow page while holding only a pin on the primary bucket
page, so the primary page is not in that record. A later record carries
the first full-page image of the primary page.
If the primary page is torn on disk and recovery replays the DELETE
before that image, redo reads the primary page only to take the cleanup
lock, with RBM_NORMAL, and the read fails the checksum and raises
"invalid page", before the image that would repair it is reached.
On master today the same page is read through block 0 with the same
RBM_NORMAL, so the failure is identical with and without the series.
0001 just reaches the page through the appended block number instead of
block 0. So this is worth fixing on its own, and the fix is orthogonal
to whether we register the page or carry its block number.
On the approaches raised so far:
- RBM_ZERO_ON_ERROR (Vignesh): it does make the read tolerate the torn
page, and a later FPI repairs it. But as Amit noted it is documented
for non-critical forks (VM, FSM) where the caller repairs, and we'd be
pointing it at a main-fork index page, which reads wrong even if it
happens to work here. I share the hesitation.
- HotStandbyActiveInReplay() guard (Amit): the cleanup lock on the
primary page exists only to keep a hot-standby scan from running in
the bucket during replay. During crash recovery and before
consistency, no such scan can exist, so there is nothing to serialize
against and the read/lock is not needed then. That lines up with why
the lock is taken at all, and it avoids reading the page in exactly
the window where the torn copy has not yet been repaired. I think
this is the most promising direction.
- Lock the bucket page even when it is registered unchanged (Amit): I'll
look at this too, together with the deadlock I described earlier in
the thread when taking the primary-page lock in _hash_freeovflpage()
after the metapage is locked.
I'd rather not pick one and bake it into this series until we've
actually tested them against Shihao's and Vignesh's reproducers (and
confirmed the HotStandbyActiveInReplay path is safe on a standby that
reaches consistency mid-bucket). I'll do that and come back with a
separate patch for the torn-page fix, since it stands on its own against
master.
Does treating it as its own fix, rather than folding it into 0001, sound
right to you? Does anyone think this should be a separate patch against
master?
Patches 0001-0003 attached, against current master.
best.
-greg
Attachments: download all (3 files, .tar.gz)
v5-0003-Remove-REGBUF_NO_CHANGE.patch (text/plain, 5.2K) download
From 9c51d256e1b7c43a3c6367dac4e04046377a182d Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:17:46 -0400
Subject: [PATCH v5 3/3] Remove REGBUF_NO_CHANGE
With the previous commits, the hash index AM no longer registers any
pin-only or otherwise-unchanged buffer, so REGBUF_NO_CHANGE has no users
left. Remove the flag and restore the invariant that every registered
buffer is content-locked and dirty: XLogRegisterBuffer() asserts it
unconditionally again.
This also reverts the defensive measures added in 27caf4ca5ae5, which
let a REGBUF_NO_CHANGE buffer skip the full-page image forced by
wal_consistency_checking: XLogRecordAssemble() no longer special-cases
the flag, and verifyBackupPageConsistency() again asserts that a
registered block carries an image. 27caf4ca5ae5 remains in the back
branches, where this hash rework is not applied.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/transam/README | 5 ----
src/backend/access/transam/xloginsert.c | 28 ++++++-----------------
src/backend/access/transam/xlogrecovery.c | 7 +-----
src/include/access/xloginsert.h | 3 ---
4 files changed, 8 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/transam/README b/src/backend/access/transam/README
index 595afa01fa7..231106270fd 100644
--- a/src/backend/access/transam/README
+++ b/src/backend/access/transam/README
@@ -586,11 +586,6 @@ void XLogRegisterBuffer(uint8 block_id, Buffer buf, uint8 flags);
XLogRegisterBufData() is included in the WAL record even if a full-page
image is taken.
- The REGBUF_NO_CHANGE flag indicates that the buffer is registered without
- being modified by this record, and possibly without an exclusive content
- lock. wal_consistency_checking does not force a full-page image for such
- a buffer.
-
void XLogRegisterData(const void *data, int len);
XLogRegisterData is used to include arbitrary data in the WAL record. If
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index cd3359434e1..2d031e38594 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -257,22 +257,13 @@ XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Assert(begininsert_called);
/*
- * Ordinarily, the buffer should be exclusive-locked (or share-exclusive
- * in case of hint bits) and marked dirty before we get here, otherwise we
- * could end up violating one of the rules in access/transam/README.
- *
- * Some callers intentionally register a clean page and never update that
- * page's LSN; in that case they can pass the flag REGBUF_NO_CHANGE to
- * bypass these checks.
+ * The buffer should be exclusive-locked (or share-exclusive in case of
+ * hint bits) and marked dirty before we get here, otherwise we could end
+ * up violating one of the rules in access/transam/README.
*/
-#ifdef USE_ASSERT_CHECKING
- if (!(flags & REGBUF_NO_CHANGE))
- {
- Assert(BufferIsDirty(buffer));
- Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
- BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
- }
-#endif
+ Assert(BufferIsDirty(buffer));
+ Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
+ BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
if (block_id >= max_registered_block_id)
{
@@ -722,13 +713,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
- *
- * Do not force an image for a REGBUF_NO_CHANGE buffer.
*/
- if (regbuf->flags & REGBUF_NO_CHANGE)
- include_image = needs_backup;
- else
- include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
+ include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..7a1de0567a8 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2488,12 +2488,7 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- /*
- * Blocks registered with REGBUF_NO_CHANGE may have no image, see
- * XLogRecordAssemble(). Nothing to compare for these.
- */
- if (!XLogRecHasBlockImage(record, block_id))
- continue;
+ Assert(XLogRecHasBlockImage(record, block_id));
if (XLogRecBlockImageApply(record, block_id))
{
diff --git a/src/include/access/xloginsert.h b/src/include/access/xloginsert.h
index 86264564ebb..ddb1a85db59 100644
--- a/src/include/access/xloginsert.h
+++ b/src/include/access/xloginsert.h
@@ -38,9 +38,6 @@
* will be skipped) */
#define REGBUF_KEEP_DATA 0x10 /* include data even if a full-page image
* is taken */
-#define REGBUF_NO_CHANGE 0x20 /* intentionally register clean buffer; no
- * image is forced for WAL consistency
- * checking */
/* prototypes for public functions in xloginsert.c: */
extern void XLogBeginInsert(void);
--
2.54.0
v5-0001-Don-t-register-pin-only-primary-bucket-pages-in-h.patch (text/plain, 22.2K) download
From 9f399e7c90fd3ac14a0fed2697f79fa77c264367 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v5 1/3] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that no scan on a hot standby is in progress in the bucket, and
none can start, while tuples are removed or moved. That lock was
obtained by registering the page (pin-only) with REGBUF_NO_CHANGE; redo
never reads data from the block, the registration existed only for the
lock. That broke the rule that a registered buffer is one the caller
holds exclusively locked and dirty, and under wal_consistency_checking
it forced a full-page image of a page a concurrent inserter could still
modify, so the record CRC was computed over shifting data.
Stop registering the primary bucket page when the record does not change
it. When the page is not one of the pages the record changes, the
operation holds only a pin on it, so the record carries the page's block
number in its main data and replay reads that block and takes a cleanup
lock on it directly, at the same point and in the same order as before.
The block number is appended only in that case, so the records are no
larger than before in the common case where the primary bucket page is
registered.
After this change hash registers only buffers it holds exclusively
locked and dirty, and there are no REGBUF_NO_CHANGE users left.
The three record formats change, so bump XLOG_PAGE_MAGIC; master only.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/auNs8b_vS2OPdTL8@floki
---
src/backend/access/hash/README | 9 +++
src/backend/access/hash/hash.c | 17 ++---
src/backend/access/hash/hash_xlog.c | 99 +++++++++++++++++----------
src/backend/access/hash/hashovfl.c | 100 ++++++++++++----------------
src/include/access/hash_xlog.h | 37 ++++++----
src/include/access/xlog_internal.h | 2 +-
6 files changed, 149 insertions(+), 115 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record then carries its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..7a79030303e 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -909,19 +909,16 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * If buf is an overflow page, the primary bucket page is not
+ * changed and we hold only a pin on it, so it is not
+ * registered. Append its block number instead, and replay
+ * takes a cleanup lock on it. It is not needed otherwise.
*/
if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
- XLogRegisterBufData(1, deletable,
+ XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_DELETE);
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..e18bb94b89f 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -469,6 +469,38 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on the primary bucket page of the bucket that a
+ * squeeze or delete record operates on, when that page is not one of the
+ * pages the record changes and so is not registered in it. Its block number
+ * is stored in the main data of the record, right after the fixed-size struct
+ * of rec_size bytes.
+ *
+ * This serializes replay against scans on a hot standby, which pin the
+ * primary bucket page for their whole duration; see the comments in the
+ * callers. The page is not modified, so nothing is done with it besides
+ * locking it. block_id must be a block of the same index registered in
+ * the record.
+ */
+static Buffer
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ BlockNumber bucket_blkno;
+ Buffer buf;
+
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -490,16 +522,12 @@ hash_xlog_move_page_contents(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 0, SizeOfHashMovePageContents);
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
}
/* replay the record for adding entries in overflow buffer */
@@ -511,7 +539,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
Size datalen;
uint16 ninserted = 0;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -550,13 +578,13 @@ hash_xlog_move_page_contents(XLogReaderState *record)
}
/* replay the record for deleting entries from overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &deletebuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &deletebuf) == BLK_NEEDS_REDO)
{
Page page;
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 2, &len);
+ ptr = XLogRecGetBlockData(record, 1, &len);
page = BufferGetPage(deletebuf);
@@ -617,17 +645,22 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ {
+ /* block 0 is absent if the primary bucket page is not modified */
+ if (XLogRecHasBlockRef(record, 0))
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashSqueezePage);
+ action = BLK_NOTFOUND;
+ }
+ }
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
else
action = BLK_NOTFOUND;
}
@@ -642,7 +675,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint16 ninserted = 0;
bool mod_wbuf = false;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -708,7 +741,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
}
/* replay the record for initializing overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &ovflbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &ovflbuf) == BLK_NEEDS_REDO)
{
Page ovflpage;
HashPageOpaque ovflopaque;
@@ -733,7 +766,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/* replay the record for page previous to the freed overflow page */
if (!xldata->is_prev_bucket_same_wrt &&
- XLogReadBufferForRedo(record, 3, &prevbuf) == BLK_NEEDS_REDO)
+ XLogReadBufferForRedo(record, 2, &prevbuf) == BLK_NEEDS_REDO)
{
Page prevpage = BufferGetPage(prevbuf);
HashPageOpaque prevopaque = HashPageGetOpaque(prevpage);
@@ -747,11 +780,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(prevbuf);
/* replay the record for page next to the freed overflow page */
- if (XLogRecHasBlockRef(record, 4))
+ if (XLogRecHasBlockRef(record, 3))
{
Buffer nextbuf;
- if (XLogReadBufferForRedo(record, 4, &nextbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 3, &nextbuf) == BLK_NEEDS_REDO)
{
Page nextpage = BufferGetPage(nextbuf);
HashPageOpaque nextopaque = HashPageGetOpaque(nextpage);
@@ -778,7 +811,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* index updates can be happening concurrently.
*/
/* replay the record for bitmap page */
- if (XLogReadBufferForRedo(record, 5, &mapbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 4, &mapbuf) == BLK_NEEDS_REDO)
{
Page mappage = BufferGetPage(mapbuf);
uint32 *freep = NULL;
@@ -788,7 +821,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
freep = HashPageGetBitmap(mappage);
- data = XLogRecGetBlockData(record, 5, &datalen);
+ data = XLogRecGetBlockData(record, 4, &datalen);
bitmap_page_bit = (uint32 *) data;
CLRBIT(freep, *bitmap_page_bit);
@@ -800,11 +833,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(mapbuf);
/* replay the record for meta page */
- if (XLogRecHasBlockRef(record, 6))
+ if (XLogRecHasBlockRef(record, 5))
{
Buffer metabuf;
- if (XLogReadBufferForRedo(record, 6, &metabuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 5, &metabuf) == BLK_NEEDS_REDO)
{
HashMetaPage metap;
Page page;
@@ -812,7 +845,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint32 *firstfree_ovflpage;
Size datalen;
- data = XLogRecGetBlockData(record, 6, &datalen);
+ data = XLogRecGetBlockData(record, 5, &datalen);
firstfree_ovflpage = (uint32 *) data;
page = BufferGetPage(metabuf);
@@ -848,16 +881,12 @@ hash_xlog_delete(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_primary_bucket_page)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 0, SizeOfHashDelete);
- action = XLogReadBufferForRedo(record, 1, &deletebuf);
+ action = XLogReadBufferForRedo(record, 0, &deletebuf);
}
/* replay the record for deleting entries in bucket page */
@@ -866,7 +895,7 @@ hash_xlog_delete(XLogReaderState *record)
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 1, &len);
+ ptr = XLogRecGetBlockData(record, 0, &len);
page = BufferGetPage(deletebuf);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..7ad934ca38f 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,6 +660,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
@@ -667,45 +672,27 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Register only the pages this record changes. The primary bucket
+ * page is registered only if it is the write page and is modified;
+ * otherwise we may hold only a pin on it, so append its block number
+ * and replay takes a cleanup lock on it.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- if (nitups > 0)
- {
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
+ if (mod_wbuf)
{
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(0, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
+ }
}
- XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(1, ovflbuf, REGBUF_STANDARD);
/*
* If prevpage and the writepage (block in which we are moving tuples
@@ -714,18 +701,18 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* writepage.
*/
if (BufferIsValid(prevbuf) && !is_prev_bucket_same_wrt)
- XLogRegisterBuffer(3, prevbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(2, prevbuf, REGBUF_STANDARD);
if (BufferIsValid(nextbuf))
- XLogRegisterBuffer(4, nextbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(3, nextbuf, REGBUF_STANDARD);
- XLogRegisterBuffer(5, mapbuf, REGBUF_STANDARD);
- XLogRegisterBufData(5, &bitmapbit, sizeof(uint32));
+ XLogRegisterBuffer(4, mapbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(4, &bitmapbit, sizeof(uint32));
if (update_metap)
{
- XLogRegisterBuffer(6, metabuf, REGBUF_STANDARD);
- XLogRegisterBufData(6, &metap->hashm_firstfree, sizeof(uint32));
+ XLogRegisterBuffer(5, metabuf, REGBUF_STANDARD);
+ XLogRegisterBufData(5, &metap->hashm_firstfree, sizeof(uint32));
}
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SQUEEZE_PAGE);
@@ -966,10 +953,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -998,25 +987,22 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, itup_offsets,
nitups * sizeof(OffsetNumber));
for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
- XLogRegisterBuffer(2, rbuf, REGBUF_STANDARD);
- XLogRegisterBufData(2, deletable,
+ XLogRegisterBuffer(1, rbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_MOVE_PAGE_CONTENTS);
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..0bb0d0590f5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,9 +129,13 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing moved tuples
- * Backup Blk 2: page from which tuples will be removed
+ * Backup Blk 0: page containing moved tuples
+ * Backup Blk 1: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
@@ -149,13 +153,18 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
- * Backup Blk 2: freed overflow page
- * Backup Blk 3: page previous to the freed overflow page
- * Backup Blk 4: page next to the freed overflow page
- * Backup Blk 5: bitmap page containing info of freed overflow page
- * Backup Blk 6: meta page
+ * Backup Blk 0: page containing tuples moved from freed overflow page, if
+ * it is modified
+ * Backup Blk 1: freed overflow page
+ * Backup Blk 2: page previous to the freed overflow page
+ * Backup Blk 3: page next to the freed overflow page
+ * Backup Blk 4: bitmap page containing info of freed overflow page
+ * Backup Blk 5: meta page
+ *
+ * The primary bucket page is registered only as block 0, when it is the
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
@@ -179,8 +188,12 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page from which tuples are deleted
+ * Backup Blk 0: page from which tuples are deleted
+ *
+ * If block 0 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
--
2.54.0
v5-0002-Add-a-recovery-test-for-the-hash-WAL-pin-only-buc.patch (text/plain, 11.4K) download
From 844c124947f013db0d178aa12a6d3412396c7a99 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v5 2/3] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/061_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 +++
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_vacuum_insert_crc.pl | 181 ++++++++++++++++++
3 files changed, 204 insertions(+)
create mode 100644 src/test/recovery/t/061_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..5051031df56 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_vacuum_insert_crc.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_vacuum_insert_crc.pl b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..aa030abd587
--- /dev/null
+++ b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
@@ -0,0 +1,181 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.54.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
@ 2026-11-11 21:11 ` Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 10:41 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-12 13:23 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
1 sibling, 3 replies; 34+ messages in thread
From: Greg Burd @ 2026-11-11 21:11 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: shihao zhong <zhong950419@gmail.com>; vignesh C <vignesh21@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
Hello,
Following up on the torn-page problem Shihao found and Vignesh
reproduced, and on Amit's comments. I reproduced it, tested the fixes,
and have reworked the series so the torn-page fix comes first.
The case of the torn-page: The bug is on master today, independent of
the pin-only rework. I ran Vignesh's reproducer (adapted so it finds
the primary bucket page from a record that registers it, rather than
from the removed bucket_blkno field) against three trees:
- plain master: recovery fails replaying the overflow DELETE, "invalid
page in block 7", before the later full-page image of block 7.
- the pin-only series: same failure, reached through the appended
block number instead of block 0.
- master + the fix: recovery succeeds and the index returns the right
rows.
The hazard was spotted during the original hash WAL work. In 2017
Robert raised it on the write-ahead-logging thread [1]:
"the page is registered and therefore an FPI will be taken if this is
the first reference to this page since the checkpoint, but
hash_xlog_delete won't restore the FPI. I think that exposes us to a
torn-page hazard. _hash_freeovflpage/hash_xlog_squeeze_page seems to
have the same disease, as does
_hash_squeezebucket/hash_xlog_move_page_contents."
Redo was then switched to XLogReadBufferForRedoExtended() so it restores
an image when the record has one, but these records register the primary
bucket page pin-only with REGBUF_NO_IMAGE, so there is nothing to
restore and the RBM_NORMAL read still reaches the torn page. So the
hazard stayed open; Shihao and Vignesh have now hit it.
On the fix: RBM_ZERO_ON_ERROR (Vignesh) does fix the reproducer, but as
Amit noted it is documented for non-critical forks where the caller
repairs, and this is a main-fork index page. Guarding the read with
InHotStandby (Amit's suggestion) also fixes it and is the right one:
- The read exists only to take the cleanup lock, which only matters to
serialize against a scan on a hot standby. When hot standby is not
active no such scan can exist, so neither the read nor the lock is
needed.
- That is exactly the window where the torn-page hazard lives. The
repairing image always precedes the point where hot standby becomes
active, so once InHotStandby is true any earlier image has already
been replayed and the page is no longer torn.
- It matches existing practice: nbtree and gist already gate their
redo cleanup-lock work on InHotStandby.
Since the bug is pre-existing, the fix is patch 0001: it stands on its
own against master, applies with or without the rework, and (the
back-branch question aside) is separate from the refactor. The rest of
the series then builds on it; in 0002 the same guard lives in the one
helper the refactor introduces, hash_xlog_lock_bucket().
0001 Fix hash index redo reading a torn primary bucket page
0002 Don't register pin-only primary bucket pages in hash WAL records
(merges the old 0001 and the four-byte optimization, and
renumbers the registered blocks per Amit's comment)
0003 Add a recovery test for the hash WAL pin-only bucket page fix
0004 Remove REGBUF_NO_CHANGE
For 0002 I folded the append-only-when-needed change into the main patch
so there is no common-case size increase at any point, and renumbered
the registered blocks so each record starts at 0 again now that the
primary bucket page is no longer block 0.
Testing (on current master): the new 068a recovery test fails on master
and on the pin-only series, and passes with 0001; the full recovery,
isolation and regress suites pass with PG_TEST_EXTRA=
wal_consistency_checking across the series.
best.
-greg
[1] https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
Attachments: download all (4 files, .tar.gz)
v6-0004-Remove-REGBUF_NO_CHANGE.patch (text/x-patch, 5.2K) download
From 709c222f2c13e62646ca53947dff6d9a6c3d1693 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:17:46 -0400
Subject: [PATCH v6 4/4] Remove REGBUF_NO_CHANGE
With the previous commits, the hash index AM no longer registers any
pin-only or otherwise-unchanged buffer, so REGBUF_NO_CHANGE has no users
left. Remove the flag and restore the invariant that every registered
buffer is content-locked and dirty: XLogRegisterBuffer() asserts it
unconditionally again.
This also reverts the defensive measures added in 27caf4ca5ae5, which
let a REGBUF_NO_CHANGE buffer skip the full-page image forced by
wal_consistency_checking: XLogRecordAssemble() no longer special-cases
the flag, and verifyBackupPageConsistency() again asserts that a
registered block carries an image. 27caf4ca5ae5 remains in the back
branches, where this hash rework is not applied.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/transam/README | 5 ----
src/backend/access/transam/xloginsert.c | 28 ++++++-----------------
src/backend/access/transam/xlogrecovery.c | 7 +-----
src/include/access/xloginsert.h | 3 ---
4 files changed, 8 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/transam/README b/src/backend/access/transam/README
index 595afa01fa7..231106270fd 100644
--- a/src/backend/access/transam/README
+++ b/src/backend/access/transam/README
@@ -586,11 +586,6 @@ void XLogRegisterBuffer(uint8 block_id, Buffer buf, uint8 flags);
XLogRegisterBufData() is included in the WAL record even if a full-page
image is taken.
- The REGBUF_NO_CHANGE flag indicates that the buffer is registered without
- being modified by this record, and possibly without an exclusive content
- lock. wal_consistency_checking does not force a full-page image for such
- a buffer.
-
void XLogRegisterData(const void *data, int len);
XLogRegisterData is used to include arbitrary data in the WAL record. If
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index cd3359434e1..2d031e38594 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -257,22 +257,13 @@ XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Assert(begininsert_called);
/*
- * Ordinarily, the buffer should be exclusive-locked (or share-exclusive
- * in case of hint bits) and marked dirty before we get here, otherwise we
- * could end up violating one of the rules in access/transam/README.
- *
- * Some callers intentionally register a clean page and never update that
- * page's LSN; in that case they can pass the flag REGBUF_NO_CHANGE to
- * bypass these checks.
+ * The buffer should be exclusive-locked (or share-exclusive in case of
+ * hint bits) and marked dirty before we get here, otherwise we could end
+ * up violating one of the rules in access/transam/README.
*/
-#ifdef USE_ASSERT_CHECKING
- if (!(flags & REGBUF_NO_CHANGE))
- {
- Assert(BufferIsDirty(buffer));
- Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
- BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
- }
-#endif
+ Assert(BufferIsDirty(buffer));
+ Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
+ BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
if (block_id >= max_registered_block_id)
{
@@ -722,13 +713,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
- *
- * Do not force an image for a REGBUF_NO_CHANGE buffer.
*/
- if (regbuf->flags & REGBUF_NO_CHANGE)
- include_image = needs_backup;
- else
- include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
+ include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..7a1de0567a8 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2488,12 +2488,7 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- /*
- * Blocks registered with REGBUF_NO_CHANGE may have no image, see
- * XLogRecordAssemble(). Nothing to compare for these.
- */
- if (!XLogRecHasBlockImage(record, block_id))
- continue;
+ Assert(XLogRecHasBlockImage(record, block_id));
if (XLogRecBlockImageApply(record, block_id))
{
diff --git a/src/include/access/xloginsert.h b/src/include/access/xloginsert.h
index 86264564ebb..ddb1a85db59 100644
--- a/src/include/access/xloginsert.h
+++ b/src/include/access/xloginsert.h
@@ -38,9 +38,6 @@
* will be skipped) */
#define REGBUF_KEEP_DATA 0x10 /* include data even if a full-page image
* is taken */
-#define REGBUF_NO_CHANGE 0x20 /* intentionally register clean buffer; no
- * image is forced for WAL consistency
- * checking */
/* prototypes for public functions in xloginsert.c: */
extern void XLogBeginInsert(void);
--
2.47.3
v6-0002-Don-t-register-pin-only-primary-bucket-pages-in-h.patch (text/x-patch, 24.5K) download
From 76d2bb84fffaa04564ceeb3ac92c38d2228010ac Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v6 2/4] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that no scan on a hot standby is in progress in the bucket, and
none can start, while tuples are removed or moved. That lock was
obtained by registering the page (pin-only) with REGBUF_NO_CHANGE; redo
never reads data from the block, the registration existed only for the
lock. That broke the rule that a registered buffer is one the caller
holds exclusively locked and dirty, and under wal_consistency_checking
it forced a full-page image of a page a concurrent inserter could still
modify, so the record CRC was computed over shifting data.
Stop registering the primary bucket page when the record does not change
it. When the page is not one of the pages the record changes, the
operation holds only a pin on it, so the record carries the page's block
number in its main data and replay reads that block and takes a cleanup
lock on it directly, at the same point and in the same order as before.
The block number is appended only in that case, so the records are no
larger than before in the common case where the primary bucket page is
registered.
After this change hash registers only buffers it holds exclusively
locked and dirty, and there are no REGBUF_NO_CHANGE users left.
The three record formats change, so bump XLOG_PAGE_MAGIC; master only.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/auNs8b_vS2OPdTL8@floki
---
src/backend/access/hash/README | 9 ++
src/backend/access/hash/hash.c | 17 ++--
src/backend/access/hash/hash_xlog.c | 139 ++++++++++++++++------------
src/backend/access/hash/hashovfl.c | 100 +++++++++-----------
src/include/access/hash_xlog.h | 37 +++++---
src/include/access/xlog_internal.h | 2 +-
6 files changed, 165 insertions(+), 139 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record then carries its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..7a79030303e 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -909,19 +909,16 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * If buf is an overflow page, the primary bucket page is not
+ * changed and we hold only a pin on it, so it is not
+ * registered. Append its block number instead, and replay
+ * takes a cleanup lock on it. It is not needed otherwise.
*/
if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
- XLogRegisterBufData(1, deletable,
+ XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_DELETE);
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 35791b087be..187de1f54ea 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -469,6 +469,54 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on the primary bucket page of the bucket that a
+ * squeeze or delete record operates on, when that page is not one of the
+ * pages the record changes and so is not registered in it. Its block number
+ * is stored in the main data of the record, right after the fixed-size struct
+ * of rec_size bytes.
+ *
+ * This serializes replay against scans on a hot standby, which pin the
+ * primary bucket page for their whole duration; see the comments in the
+ * callers. The page is not modified, so nothing is done with it besides
+ * locking it. block_id must be a block of the same index registered in
+ * the record.
+ */
+static Buffer
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ BlockNumber bucket_blkno;
+ Buffer buf;
+
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
+ /*
+ * The cleanup lock on the primary bucket page serializes replay against
+ * scans on a hot standby, which pin the page for their whole duration.
+ * When hot standby is not active no such scan can exist, so there is
+ * nothing to serialize against and we need not read or lock the page.
+ *
+ * Skipping the read also sidesteps a torn copy of the page whose
+ * repairing full-page image comes later in the WAL: that hazard exists
+ * only before consistency is reached, which is before hot standby becomes
+ * active, so once InHotStandby is true any earlier image has already been
+ * replayed and the page is no longer torn. Redo never uses the page's
+ * contents here in any case.
+ */
+ if (!InHotStandby)
+ return InvalidBuffer;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -490,24 +538,12 @@ hash_xlog_move_page_contents(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. When hot standby is not active no such scan can exist,
- * so we need not read or lock the page. Skipping the read also
- * sidesteps a torn copy of the page whose repairing full-page image
- * comes later in the WAL: that hazard exists only before consistency
- * is reached, which is before hot standby becomes active, so once
- * InHotStandby is true any earlier image has already been replayed.
- * We do not use the page contents here in any case.
- */
- if (InHotStandby)
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 0, SizeOfHashMovePageContents);
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
}
/* replay the record for adding entries in overflow buffer */
@@ -519,7 +555,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
Size datalen;
uint16 ninserted = 0;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -558,13 +594,13 @@ hash_xlog_move_page_contents(XLogReaderState *record)
}
/* replay the record for deleting entries from overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &deletebuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &deletebuf) == BLK_NEEDS_REDO)
{
Page page;
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 2, &len);
+ ptr = XLogRecGetBlockData(record, 1, &len);
page = BufferGetPage(deletebuf);
@@ -625,25 +661,22 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ {
+ /* block 0 is absent if the primary bucket page is not modified */
+ if (XLogRecHasBlockRef(record, 0))
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashSqueezePage);
+ action = BLK_NOTFOUND;
+ }
+ }
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. When hot standby is not active no such scan can exist,
- * so we need not read or lock the page. Skipping the read also
- * sidesteps a torn copy of the page whose repairing full-page image
- * comes later in the WAL: that hazard exists only before consistency
- * is reached, which is before hot standby becomes active, so once
- * InHotStandby is true any earlier image has already been replayed.
- * We do not use the page contents here in any case.
- */
- if (InHotStandby)
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 1, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
else
action = BLK_NOTFOUND;
}
@@ -658,7 +691,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint16 ninserted = 0;
bool mod_wbuf = false;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -724,7 +757,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
}
/* replay the record for initializing overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &ovflbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &ovflbuf) == BLK_NEEDS_REDO)
{
Page ovflpage;
HashPageOpaque ovflopaque;
@@ -749,7 +782,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/* replay the record for page previous to the freed overflow page */
if (!xldata->is_prev_bucket_same_wrt &&
- XLogReadBufferForRedo(record, 3, &prevbuf) == BLK_NEEDS_REDO)
+ XLogReadBufferForRedo(record, 2, &prevbuf) == BLK_NEEDS_REDO)
{
Page prevpage = BufferGetPage(prevbuf);
HashPageOpaque prevopaque = HashPageGetOpaque(prevpage);
@@ -763,11 +796,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(prevbuf);
/* replay the record for page next to the freed overflow page */
- if (XLogRecHasBlockRef(record, 4))
+ if (XLogRecHasBlockRef(record, 3))
{
Buffer nextbuf;
- if (XLogReadBufferForRedo(record, 4, &nextbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 3, &nextbuf) == BLK_NEEDS_REDO)
{
Page nextpage = BufferGetPage(nextbuf);
HashPageOpaque nextopaque = HashPageGetOpaque(nextpage);
@@ -794,7 +827,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* index updates can be happening concurrently.
*/
/* replay the record for bitmap page */
- if (XLogReadBufferForRedo(record, 5, &mapbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 4, &mapbuf) == BLK_NEEDS_REDO)
{
Page mappage = BufferGetPage(mapbuf);
uint32 *freep = NULL;
@@ -804,7 +837,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
freep = HashPageGetBitmap(mappage);
- data = XLogRecGetBlockData(record, 5, &datalen);
+ data = XLogRecGetBlockData(record, 4, &datalen);
bitmap_page_bit = (uint32 *) data;
CLRBIT(freep, *bitmap_page_bit);
@@ -816,11 +849,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(mapbuf);
/* replay the record for meta page */
- if (XLogRecHasBlockRef(record, 6))
+ if (XLogRecHasBlockRef(record, 5))
{
Buffer metabuf;
- if (XLogReadBufferForRedo(record, 6, &metabuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 5, &metabuf) == BLK_NEEDS_REDO)
{
HashMetaPage metap;
Page page;
@@ -828,7 +861,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint32 *firstfree_ovflpage;
Size datalen;
- data = XLogRecGetBlockData(record, 6, &datalen);
+ data = XLogRecGetBlockData(record, 5, &datalen);
firstfree_ovflpage = (uint32 *) data;
page = BufferGetPage(metabuf);
@@ -864,24 +897,12 @@ hash_xlog_delete(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_primary_bucket_page)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. When hot standby is not active no such scan can exist,
- * so we need not read or lock the page. Skipping the read also
- * sidesteps a torn copy of the page whose repairing full-page image
- * comes later in the WAL: that hazard exists only before consistency
- * is reached, which is before hot standby becomes active, so once
- * InHotStandby is true any earlier image has already been replayed.
- * We do not use the page contents here in any case.
- */
- if (InHotStandby)
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_bucket(record, 0, SizeOfHashDelete);
- action = XLogReadBufferForRedo(record, 1, &deletebuf);
+ action = XLogReadBufferForRedo(record, 0, &deletebuf);
}
/* replay the record for deleting entries in bucket page */
@@ -890,7 +911,7 @@ hash_xlog_delete(XLogReaderState *record)
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 1, &len);
+ ptr = XLogRecGetBlockData(record, 0, &len);
page = BufferGetPage(deletebuf);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..7ad934ca38f 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,6 +660,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
@@ -667,45 +672,27 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Register only the pages this record changes. The primary bucket
+ * page is registered only if it is the write page and is modified;
+ * otherwise we may hold only a pin on it, so append its block number
+ * and replay takes a cleanup lock on it.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- if (nitups > 0)
- {
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
+ if (mod_wbuf)
{
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(0, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
+ }
}
- XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(1, ovflbuf, REGBUF_STANDARD);
/*
* If prevpage and the writepage (block in which we are moving tuples
@@ -714,18 +701,18 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* writepage.
*/
if (BufferIsValid(prevbuf) && !is_prev_bucket_same_wrt)
- XLogRegisterBuffer(3, prevbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(2, prevbuf, REGBUF_STANDARD);
if (BufferIsValid(nextbuf))
- XLogRegisterBuffer(4, nextbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(3, nextbuf, REGBUF_STANDARD);
- XLogRegisterBuffer(5, mapbuf, REGBUF_STANDARD);
- XLogRegisterBufData(5, &bitmapbit, sizeof(uint32));
+ XLogRegisterBuffer(4, mapbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(4, &bitmapbit, sizeof(uint32));
if (update_metap)
{
- XLogRegisterBuffer(6, metabuf, REGBUF_STANDARD);
- XLogRegisterBufData(6, &metap->hashm_firstfree, sizeof(uint32));
+ XLogRegisterBuffer(5, metabuf, REGBUF_STANDARD);
+ XLogRegisterBufData(5, &metap->hashm_firstfree, sizeof(uint32));
}
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SQUEEZE_PAGE);
@@ -966,10 +953,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -998,25 +987,22 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, itup_offsets,
nitups * sizeof(OffsetNumber));
for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
- XLogRegisterBuffer(2, rbuf, REGBUF_STANDARD);
- XLogRegisterBufData(2, deletable,
+ XLogRegisterBuffer(1, rbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_MOVE_PAGE_CONTENTS);
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..0bb0d0590f5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,9 +129,13 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing moved tuples
- * Backup Blk 2: page from which tuples will be removed
+ * Backup Blk 0: page containing moved tuples
+ * Backup Blk 1: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
@@ -149,13 +153,18 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
- * Backup Blk 2: freed overflow page
- * Backup Blk 3: page previous to the freed overflow page
- * Backup Blk 4: page next to the freed overflow page
- * Backup Blk 5: bitmap page containing info of freed overflow page
- * Backup Blk 6: meta page
+ * Backup Blk 0: page containing tuples moved from freed overflow page, if
+ * it is modified
+ * Backup Blk 1: freed overflow page
+ * Backup Blk 2: page previous to the freed overflow page
+ * Backup Blk 3: page next to the freed overflow page
+ * Backup Blk 4: bitmap page containing info of freed overflow page
+ * Backup Blk 5: meta page
+ *
+ * The primary bucket page is registered only as block 0, when it is the
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
@@ -179,8 +188,12 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page from which tuples are deleted
+ * Backup Blk 0: page from which tuples are deleted
+ *
+ * If block 0 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
--
2.47.3
v6-0001-Fix-hash-index-redo-reading-a-torn-primary-bucket.patch (text/x-patch, 11.5K) download
From 33501fe1747a460c2e1ec57edd3ebaeacc07dec7 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Wed, 11 Nov 2026 20:58:41 +0000
Subject: [PATCH v6 1/4] Fix hash index redo reading a torn primary bucket page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This needs data checksums (or
full_page_writes catching the tear) to be detected, and the right
interleaving of a VACUUM that removes tuples from an overflow page while
the primary bucket page is unmodified, followed by a later modification
of the primary page.
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans.
When hot standby is not active no such scan can exist, so the read and
lock are unnecessary; skip them. That also avoids reading the page in
the only window where its torn on-disk copy has not yet been repaired,
since the repairing image always precedes the point where hot standby
becomes active. nbtree and gist already gate redo cleanup-lock work on
InHotStandby for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 42 ++++--
src/test/recovery/meson.build | 1 +
...68a_hash_torn_primary_page_delete_first.pl | 142 ++++++++++++++++++
3 files changed, 176 insertions(+), 9 deletions(-)
create mode 100644 src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..35791b087be 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -494,10 +494,18 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. When hot standby is not active no such scan can exist,
+ * so we need not read or lock the page. Skipping the read also
+ * sidesteps a torn copy of the page whose repairing full-page image
+ * comes later in the WAL: that hazard exists only before consistency
+ * is reached, which is before hot standby becomes active, so once
+ * InHotStandby is true any earlier image has already been replayed.
+ * We do not use the page contents here in any case.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (InHotStandby)
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -621,10 +629,18 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. When hot standby is not active no such scan can exist,
+ * so we need not read or lock the page. Skipping the read also
+ * sidesteps a torn copy of the page whose repairing full-page image
+ * comes later in the WAL: that hazard exists only before consistency
+ * is reached, which is before hot standby becomes active, so once
+ * InHotStandby is true any earlier image has already been replayed.
+ * We do not use the page contents here in any case.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (InHotStandby)
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -852,10 +868,18 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. When hot standby is not active no such scan can exist,
+ * so we need not read or lock the page. Skipping the read also
+ * sidesteps a torn copy of the page whose repairing full-page image
+ * comes later in the WAL: that hazard exists only before consistency
+ * is reached, which is before hot standby becomes active, so once
+ * InHotStandby is true any earlier image has already been replayed.
+ * We do not use the page contents here in any case.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (InHotStandby)
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..06b649be2aa 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/068a_hash_torn_primary_page_delete_first.pl',
],
},
}
diff --git a/src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl b/src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl
new file mode 100644
index 00000000000..e61a0b98885
--- /dev/null
+++ b/src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl
@@ -0,0 +1,142 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test crash recovery when the primary bucket page of a hash bucket is torn,
+# and the full-page image that repairs it comes after the record that reads it.
+#
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$node->start;
+
+is($node->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $redo = $node->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# The entries of ids 451-600 are on the overflow page, those of ids 1-50 on the
+# primary page. The DELETE for the overflow page comes first; the VACUUM of
+# the primary page then changes it for the first time since the checkpoint, so
+# its record carries the full-page image of the page.
+$node->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$node->safe_psql('postgres', 'VACUUM t');
+$node->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$node->safe_psql('postgres', 'VACUUM t');
+
+my $relpath = $node->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $node->safe_psql('postgres', 'SHOW block_size');
+$node->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# Read the Hash records after the checkpoint.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--rmgr' => 'Hash',
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary bucket page's block number is not a registered block of the
+# overflow-page DELETE (the record carries it only as appended main data), so
+# find it from a record that does register it: a DELETE or SQUEEZE_PAGE marked
+# is_primary T references the primary bucket page as its first block.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #0: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout;
+
+# The overflow-page DELETE (is_primary F) reads the primary bucket page
+# pin-only to take the cleanup lock; it must come before the primary page's
+# first full-page image.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete,
+ 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout;
+
+# Where the first full-page image of the primary page is.
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+$node->stop('immediate');
+
+# Simulate a torn write of the primary page: keep the first half of its block
+# and overwrite the second half.
+if (defined $pblk)
+{
+ my $path = $node->data_dir . '/' . $relpath;
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $started = $node->start(fail_ok => 1);
+ok($started, 'crash recovery succeeds');
+if ($started)
+{
+ is( $node->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'the hash index gives the right result after recovery');
+ $node->stop;
+}
+else
+{
+ my $log = slurp_file($node->logfile);
+ diag("the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.47.3
v6-0003-Add-a-recovery-test-for-the-hash-WAL-pin-only-buc.patch (text/x-patch, 11.5K) download
From 0742d3d2d6022703fc154717f1c2270524aff7a1 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v6 3/4] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/061_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 +++
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_vacuum_insert_crc.pl | 181 ++++++++++++++++++
3 files changed, 204 insertions(+)
create mode 100644 src/test/recovery/t/061_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index 06b649be2aa..1859ff6f2c2 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_vacuum_insert_crc.pl',
't/068a_hash_torn_primary_page_delete_first.pl',
],
},
diff --git a/src/test/recovery/t/061_hash_vacuum_insert_crc.pl b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..aa030abd587
--- /dev/null
+++ b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
@@ -0,0 +1,181 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.47.3
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-12 06:39 ` vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2 siblings, 1 reply; 34+ messages in thread
From: vignesh C @ 2026-11-12 06:39 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
On Thu, 12 Nov 2026 at 02:41, Greg Burd <greg@burd.me> wrote:
>
> Hello,
>
> Following up on the torn-page problem Shihao found and Vignesh
> reproduced, and on Amit's comments. I reproduced it, tested the fixes,
> and have reworked the series so the torn-page fix comes first.
>
> The case of the torn-page: The bug is on master today, independent of
> the pin-only rework. I ran Vignesh's reproducer (adapted so it finds
> the primary bucket page from a record that registers it, rather than
> from the removed bucket_blkno field) against three trees:
>
> - plain master: recovery fails replaying the overflow DELETE, "invalid
> page in block 7", before the later full-page image of block 7.
> - the pin-only series: same failure, reached through the appended
> block number instead of block 0.
> - master + the fix: recovery succeeds and the index returns the right
> rows.
>
> The hazard was spotted during the original hash WAL work. In 2017
> Robert raised it on the write-ahead-logging thread [1]:
>
> "the page is registered and therefore an FPI will be taken if this is
> the first reference to this page since the checkpoint, but
> hash_xlog_delete won't restore the FPI. I think that exposes us to a
> torn-page hazard. _hash_freeovflpage/hash_xlog_squeeze_page seems to
> have the same disease, as does
> _hash_squeezebucket/hash_xlog_move_page_contents."
>
> Redo was then switched to XLogReadBufferForRedoExtended() so it restores
> an image when the record has one, but these records register the primary
> bucket page pin-only with REGBUF_NO_IMAGE, so there is nothing to
> restore and the RBM_NORMAL read still reaches the torn page. So the
> hazard stayed open; Shihao and Vignesh have now hit it.
>
> On the fix: RBM_ZERO_ON_ERROR (Vignesh) does fix the reproducer, but as
> Amit noted it is documented for non-critical forks where the caller
> repairs, and this is a main-fork index page. Guarding the read with
> InHotStandby (Amit's suggestion) also fixes it and is the right one:
>
> - The read exists only to take the cleanup lock, which only matters to
> serialize against a scan on a hot standby. When hot standby is not
> active no such scan can exist, so neither the read nor the lock is
> needed.
> - That is exactly the window where the torn-page hazard lives. The
> repairing image always precedes the point where hot standby becomes
> active, so once InHotStandby is true any earlier image has already
> been replayed and the page is no longer torn.
> - It matches existing practice: nbtree and gist already gate their
> redo cleanup-lock work on InHotStandby.
>
> Since the bug is pre-existing, the fix is patch 0001: it stands on its
> own against master, applies with or without the rework, and (the
> back-branch question aside) is separate from the refactor.
The fix skips reading and acquiring the cleanup lock on the primary
bucket page unless 'InHotStandby' is true. This works for crash
recovery, and the first test (068a) passes. However, 'InHotStandby'
does not mean that hot standby is ready to accept queries. It becomes
true as soon as the first 'XLOG_RUNNING_XACTS' record is replayed,
which happens shortly after the redo pointer is reached, well before
recovery reaches consistency. With 'hot_standby = on', redo can
therefore still read the page during this window.
A base backup can contain a torn copy of the page if it is written
while the backup files are being copied. The full-page image for that
page is then present in WAL generated after the backup starts. The
DELETE record for the overflow page can precede that image, while the
standby reaches consistency only after the backup ends, by which time
the image should have been replayed.
The attached test (068b) reproduces this scenario: a) Takes a
low-level backup using 'pg_backup_start()'. b) While the backup is in
progress, runs VACUUM to generate a DELETE record for the overflow
page, followed by another VACUUM that modifies the primary page for
the first time since the backup's checkpoint. The latter record
therefore includes a full-page image of the primary page. c) Tears the
backup copy of the primary page. d) Starts a standby with 'hot_standby
= on' using that backup.
With the fix, the standby fails to start:
FATAL: invalid page in block 7 of relation "base/5/16387"
CONTEXT: WAL redo at 0/020099A0 for Hash/DELETE: ... is_primary F;
blkref #0: ... blk 7; blkref #1: ... blk 10 FPW
The attached patch (0001) uses 'HotStandbyActiveInReplay()' instead.
This becomes true only after recovery has reached consistency and the
postmaster has been notified that connections can be accepted. Since
no scans can be running before that point, there is no need to read or
lock the primary bucket page earlier. By then, any full-page image
needed to repair a torn page should also have been replayed.
How about changing InHotStandby to HotStandbyActiveInReplay to fix this issue?
Regards,
Vignesh
Attachments:
068b_hash_torn_primary_page_standby.pl (text/x-perl-script, 5.7K) download
# Copyright (c) 2026, PostgreSQL Global Development Group
# Test a standby that starts from a base backup whose copy of the primary
# bucket page of a hash bucket is torn, and the full-page image that repairs it
# comes after the record that reads it.
#
use strict;
use warnings FATAL => 'all';
use File::Path qw(rmtree);
use IPC::Run;
use PostgreSQL::Test::Cluster;
use PostgreSQL::Test::Utils;
use Test::More;
my $primary = PostgreSQL::Test::Cluster->new('primary');
$primary->init(allows_streaming => 1);
$primary->append_conf(
'postgresql.conf', qq{
autovacuum = off
fsync = off
full_page_writes = on
checkpoint_timeout = 1h
});
$primary->start;
is($primary->safe_psql('postgres', 'SHOW data_checksums'),
'on', 'premise: data checksums are on');
# One bucket receives every key: a primary page holding about 407 entries and
# an overflow page with the rest.
$primary->safe_psql(
'postgres', q{
CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
CREATE INDEX t_i ON t USING hash (k);
INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
});
my $relpath = $primary->safe_psql('postgres',
q{SELECT pg_relation_filepath('t_i')});
my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
# Start a low-level backup, which does a checkpoint, and copy the files.
my $backup_name = 'torn';
my $backup_dir = $primary->backup_dir . '/' . $backup_name;
my $psql = $primary->background_psql('postgres');
$psql->query_safe("SET client_min_messages TO WARNING");
$psql->set_query_timer_restart;
$psql->query_safe("select pg_backup_start('torn primary page', true)");
my $redo = $primary->safe_psql('postgres',
'SELECT redo_lsn FROM pg_control_checkpoint()');
PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
unlink("$backup_dir/postmaster.pid")
or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
unlink("$backup_dir/postmaster.opts")
or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
rmtree("$backup_dir/pg_wal")
or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
mkdir("$backup_dir/pg_wal");
# While the backup is in progress: the entries of ids 451-600 are on the
# overflow page, those of ids 1-50 on the primary page. The DELETE for the
# overflow page comes first; the VACUUM of the primary page then changes it for
# the first time since the checkpoint of the backup, so its record carries the
# full-page image of the page.
$primary->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
$primary->safe_psql('postgres', 'VACUUM t');
$primary->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
$primary->safe_psql('postgres', 'VACUUM t');
$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
# Read the Hash records after the redo pointer of the backup.
my ($stdout, $stderr);
IPC::Run::run(
[
'pg_waldump',
'--path' => $primary->data_dir . '/pg_wal',
'--start' => $redo,
'--rmgr' => 'Hash',
],
'>' => \$stdout,
'2>' => \$stderr);
my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
# block 1, the page that is changed.
my $pblk;
for my $r (@records)
{
if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
&& $r =~ /blkref #1: rel \S+ blk (\d+)/)
{
$pblk = $1;
last;
}
}
ok(defined $pblk, 'premise: found the primary bucket page')
or diag $stdout;
# The first DELETE for an overflow page.
my ($idx_delete) =
grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
ok(defined $idx_delete,
'premise: VACUUM wrote a DELETE for an overflow page')
or diag $stdout;
# Where the first full-page image of the primary page is, relative to the
# DELETE for the overflow page.
my ($idx_fpi) =
defined $pblk
? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
0 .. $#records
: ();
ok(defined $idx_fpi,
'premise: the primary page got a full-page image after the checkpoint')
or diag $stdout;
if (defined $idx_delete && defined $idx_fpi)
{
cmp_ok($idx_delete, '<', $idx_fpi,
'premise: the DELETE comes before the image of the primary page');
}
# The copy of the primary page in the backup is torn: keep the first half of
# its block and overwrite the second half.
if (defined $pblk)
{
my $path = "$backup_dir/$relpath";
open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
syswrite($fh, $junk) == $bs / 2 or die "write: $!";
close($fh);
}
# End the backup, and save backup_label into the backup.
my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
$psql->quit;
open(my $fh, '>', "$backup_dir/backup_label")
or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
print $fh $backup_label;
close($fh);
# Start a hot standby from the backup. Replay starts at the redo pointer of
# the backup, replays the DELETE for the overflow page first, and reaches the
# consistency point only after the end of the backup, after the full-page
# image of the primary page.
my $standby = PostgreSQL::Test::Cluster->new('standby');
$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
$standby->append_conf('postgresql.conf', 'hot_standby = on');
my $started = $standby->start(fail_ok => 1);
ok($started, 'the standby starts');
if ($started)
{
$primary->wait_for_catchup($standby);
is( $standby->safe_psql(
'postgres',
q{SET enable_seqscan = off; SET enable_bitmapscan = off;
SELECT count(*) FROM t WHERE k = 1}),
'400',
'the hash index gives the right result on the standby');
}
else
{
my $log = slurp_file($standby->logfile);
diag("the standby did not start; the log has:\n"
. join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
}
done_testing();
Use_HotStandbyActiveInReplay_to_skip_primary_bucket.patch (application/octet-stream, 5.8K) download
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 35791b087be..e8ad5804eaf 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -496,15 +497,15 @@ hash_xlog_move_page_contents(XLogReaderState *record)
/*
* The cleanup lock on the primary bucket page serializes replay
* against scans on a hot standby, which pin the page for their whole
- * duration. When hot standby is not active no such scan can exist,
- * so we need not read or lock the page. Skipping the read also
- * sidesteps a torn copy of the page whose repairing full-page image
- * comes later in the WAL: that hazard exists only before consistency
- * is reached, which is before hot standby becomes active, so once
- * InHotStandby is true any earlier image has already been replayed.
- * We do not use the page contents here in any case.
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed.
*/
- if (InHotStandby)
+ if (HotStandbyActiveInReplay())
(void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -631,15 +632,15 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/*
* The cleanup lock on the primary bucket page serializes replay
* against scans on a hot standby, which pin the page for their whole
- * duration. When hot standby is not active no such scan can exist,
- * so we need not read or lock the page. Skipping the read also
- * sidesteps a torn copy of the page whose repairing full-page image
- * comes later in the WAL: that hazard exists only before consistency
- * is reached, which is before hot standby becomes active, so once
- * InHotStandby is true any earlier image has already been replayed.
- * We do not use the page contents here in any case.
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed.
*/
- if (InHotStandby)
+ if (HotStandbyActiveInReplay())
(void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
@@ -870,15 +871,15 @@ hash_xlog_delete(XLogReaderState *record)
/*
* The cleanup lock on the primary bucket page serializes replay
* against scans on a hot standby, which pin the page for their whole
- * duration. When hot standby is not active no such scan can exist,
- * so we need not read or lock the page. Skipping the read also
- * sidesteps a torn copy of the page whose repairing full-page image
- * comes later in the WAL: that hazard exists only before consistency
- * is reached, which is before hot standby becomes active, so once
- * InHotStandby is true any earlier image has already been replayed.
- * We do not use the page contents here in any case.
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed.
*/
- if (InHotStandby)
+ if (HotStandbyActiveInReplay())
(void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..e091a3e178b 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -390,7 +390,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4589,7 +4588,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 8786b6d3a8e..11d3eadef3e 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -216,6 +216,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
@ 2026-11-12 13:25 ` Greg Burd <greg@burd.me>
2026-11-12 16:12 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Joao Rito <joaovictor.rito@gmail.com>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
0 siblings, 2 replies; 34+ messages in thread
From: Greg Burd @ 2026-11-12 13:25 UTC (permalink / raw)
To: vignesh C <vignesh21@gmail.com>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
Hello,
Thanks Vignesh for catching that, and the 068b test.
Also, thanks Hayato-san for the review and comments.
Agreed, InHotStandby becomes true as soon as the first
XLOG_RUNNING_XACTS is replayed, well before recovery reaches
consistency, so with hot_standby = on redo can still read the torn page
in that window. Thanks for the 068b reproducer.
v7 uses HotStandbyActiveInReplay() instead, as you suggested. That is
true only after recovery has reached consistency and the postmaster has
been told connections can start, so there is no scan to serialize
against before then, and by then any full-page image that repairs the
page has been replayed. I made HotStandbyActiveInReplay() extern for
this. 068b now passes, and so does 068a.
I folded your 068b into 0001 next to 068a, with one change: the primary
bucket page is found from blkref #0 or #1, since after 0002 the page is
registered as block 0 rather than 1 when it is the modified page, and
the test runs against the whole series as well as master.
I've applied both of Hayato-san's comments in 0002:
hash_xlog_lock_bucket() is renamed to hash_xlog_lock_primary_bucket(),
and the "block 0 is absent" comment now reads:
/*
* If the primary bucket page is modified, it is registered as block 0
* and read for redo. Otherwise, acquire its cleanup lock separately.
*/
v7:
0001 Fix hash index redo reading a torn primary bucket page
(now with 068a and 068b, and HotStandbyActiveInReplay)
0002 Don't register pin-only primary bucket pages in hash WAL records
(hash_xlog_lock_primary_bucket, carries the same guard)
0003 Add a recovery test for the hash WAL pin-only bucket page fix
0004 Remove REGBUF_NO_CHANGE
0001 stands on its own against master; the rest build on it.
best.
-greg
Attachments: download all (4 files, .tar.gz)
v7-0002-Don-t-register-pin-only-primary-bucket-pages-in-h.patch (text/x-patch, 24.6K) download
From 29eb96c75c70d9b593f8acad54c5aec1704c81c8 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v7 2/4] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that no scan on a hot standby is in progress in the bucket, and
none can start, while tuples are removed or moved. That lock was
obtained by registering the page (pin-only) with REGBUF_NO_CHANGE; redo
never reads data from the block, the registration existed only for the
lock. That broke the rule that a registered buffer is one the caller
holds exclusively locked and dirty, and under wal_consistency_checking
it forced a full-page image of a page a concurrent inserter could still
modify, so the record CRC was computed over shifting data.
Stop registering the primary bucket page when the record does not change
it. When the page is not one of the pages the record changes, the
operation holds only a pin on it, so the record carries the page's block
number in its main data and replay reads that block and takes a cleanup
lock on it directly, at the same point and in the same order as before.
The block number is appended only in that case, so the records are no
larger than before in the common case where the primary bucket page is
registered.
After this change hash registers only buffers it holds exclusively
locked and dirty, and there are no REGBUF_NO_CHANGE users left.
The three record formats change, so bump XLOG_PAGE_MAGIC; master only.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/auNs8b_vS2OPdTL8@floki
---
src/backend/access/hash/README | 9 ++
src/backend/access/hash/hash.c | 17 ++--
src/backend/access/hash/hash_xlog.c | 139 ++++++++++++++++------------
src/backend/access/hash/hashovfl.c | 100 +++++++++-----------
src/include/access/hash_xlog.h | 37 +++++---
src/include/access/xlog_internal.h | 2 +-
6 files changed, 166 insertions(+), 138 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record then carries its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..7a79030303e 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -909,19 +909,16 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * If buf is an overflow page, the primary bucket page is not
+ * changed and we hold only a pin on it, so it is not
+ * registered. Append its block number instead, and replay
+ * takes a cleanup lock on it. It is not needed otherwise.
*/
if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
- XLogRegisterBufData(1, deletable,
+ XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_DELETE);
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e1318bf97db..bad5bccb4e1 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -470,6 +470,52 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on the primary bucket page of the bucket that a
+ * squeeze or delete record operates on, when that page is not one of the
+ * pages the record changes and so is not registered in it. Its block number
+ * is stored in the main data of the record, right after the fixed-size struct
+ * of rec_size bytes.
+ *
+ * This serializes replay against scans on a hot standby, which pin the
+ * primary bucket page for their whole duration; see the comments in the
+ * callers. The page is not modified, so nothing is done with it besides
+ * locking it. block_id must be a block of the same index registered in
+ * the record.
+ */
+static Buffer
+hash_xlog_lock_primary_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ BlockNumber bucket_blkno;
+ Buffer buf;
+
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
+ /*
+ * The cleanup lock on the primary bucket page serializes replay against
+ * scans on a hot standby, which pin the page for their whole duration.
+ * Scans can run only once hot standby accepts queries, so until then we
+ * need not read or lock the page. Skipping the read also sidesteps a torn
+ * copy of the page whose repairing full-page image comes later in the WAL:
+ * that hazard exists only before consistency is reached, and queries are
+ * accepted only after that, so once HotStandbyActiveInReplay() is true any
+ * earlier image has already been replayed. Redo never uses the page's
+ * contents here in any case.
+ */
+ if (!HotStandbyActiveInReplay())
+ return InvalidBuffer;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -491,24 +537,12 @@ hash_xlog_move_page_contents(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
- */
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashMovePageContents);
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
}
/* replay the record for adding entries in overflow buffer */
@@ -520,7 +554,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
Size datalen;
uint16 ninserted = 0;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -559,13 +593,13 @@ hash_xlog_move_page_contents(XLogReaderState *record)
}
/* replay the record for deleting entries from overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &deletebuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &deletebuf) == BLK_NEEDS_REDO)
{
Page page;
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 2, &len);
+ ptr = XLogRecGetBlockData(record, 1, &len);
page = BufferGetPage(deletebuf);
@@ -626,25 +660,26 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
- else
{
/*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
+ * If the primary bucket page is modified, it is registered as block
+ * 0 and read for redo. Otherwise, acquire its cleanup lock
+ * separately.
*/
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (XLogRecHasBlockRef(record, 0))
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
+ action = BLK_NOTFOUND;
+ }
+ }
+ else
+ {
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
else
action = BLK_NOTFOUND;
}
@@ -659,7 +694,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint16 ninserted = 0;
bool mod_wbuf = false;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -725,7 +760,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
}
/* replay the record for initializing overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &ovflbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &ovflbuf) == BLK_NEEDS_REDO)
{
Page ovflpage;
HashPageOpaque ovflopaque;
@@ -750,7 +785,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/* replay the record for page previous to the freed overflow page */
if (!xldata->is_prev_bucket_same_wrt &&
- XLogReadBufferForRedo(record, 3, &prevbuf) == BLK_NEEDS_REDO)
+ XLogReadBufferForRedo(record, 2, &prevbuf) == BLK_NEEDS_REDO)
{
Page prevpage = BufferGetPage(prevbuf);
HashPageOpaque prevopaque = HashPageGetOpaque(prevpage);
@@ -764,11 +799,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(prevbuf);
/* replay the record for page next to the freed overflow page */
- if (XLogRecHasBlockRef(record, 4))
+ if (XLogRecHasBlockRef(record, 3))
{
Buffer nextbuf;
- if (XLogReadBufferForRedo(record, 4, &nextbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 3, &nextbuf) == BLK_NEEDS_REDO)
{
Page nextpage = BufferGetPage(nextbuf);
HashPageOpaque nextopaque = HashPageGetOpaque(nextpage);
@@ -795,7 +830,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* index updates can be happening concurrently.
*/
/* replay the record for bitmap page */
- if (XLogReadBufferForRedo(record, 5, &mapbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 4, &mapbuf) == BLK_NEEDS_REDO)
{
Page mappage = BufferGetPage(mapbuf);
uint32 *freep = NULL;
@@ -805,7 +840,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
freep = HashPageGetBitmap(mappage);
- data = XLogRecGetBlockData(record, 5, &datalen);
+ data = XLogRecGetBlockData(record, 4, &datalen);
bitmap_page_bit = (uint32 *) data;
CLRBIT(freep, *bitmap_page_bit);
@@ -817,11 +852,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(mapbuf);
/* replay the record for meta page */
- if (XLogRecHasBlockRef(record, 6))
+ if (XLogRecHasBlockRef(record, 5))
{
Buffer metabuf;
- if (XLogReadBufferForRedo(record, 6, &metabuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 5, &metabuf) == BLK_NEEDS_REDO)
{
HashMetaPage metap;
Page page;
@@ -829,7 +864,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint32 *firstfree_ovflpage;
Size datalen;
- data = XLogRecGetBlockData(record, 6, &datalen);
+ data = XLogRecGetBlockData(record, 5, &datalen);
firstfree_ovflpage = (uint32 *) data;
page = BufferGetPage(metabuf);
@@ -865,24 +900,12 @@ hash_xlog_delete(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_primary_bucket_page)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
- */
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashDelete);
- action = XLogReadBufferForRedo(record, 1, &deletebuf);
+ action = XLogReadBufferForRedo(record, 0, &deletebuf);
}
/* replay the record for deleting entries in bucket page */
@@ -891,7 +914,7 @@ hash_xlog_delete(XLogReaderState *record)
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 1, &len);
+ ptr = XLogRecGetBlockData(record, 0, &len);
page = BufferGetPage(deletebuf);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..7ad934ca38f 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,6 +660,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
@@ -667,45 +672,27 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Register only the pages this record changes. The primary bucket
+ * page is registered only if it is the write page and is modified;
+ * otherwise we may hold only a pin on it, so append its block number
+ * and replay takes a cleanup lock on it.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- if (nitups > 0)
- {
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
+ if (mod_wbuf)
{
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(0, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
+ }
}
- XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(1, ovflbuf, REGBUF_STANDARD);
/*
* If prevpage and the writepage (block in which we are moving tuples
@@ -714,18 +701,18 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* writepage.
*/
if (BufferIsValid(prevbuf) && !is_prev_bucket_same_wrt)
- XLogRegisterBuffer(3, prevbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(2, prevbuf, REGBUF_STANDARD);
if (BufferIsValid(nextbuf))
- XLogRegisterBuffer(4, nextbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(3, nextbuf, REGBUF_STANDARD);
- XLogRegisterBuffer(5, mapbuf, REGBUF_STANDARD);
- XLogRegisterBufData(5, &bitmapbit, sizeof(uint32));
+ XLogRegisterBuffer(4, mapbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(4, &bitmapbit, sizeof(uint32));
if (update_metap)
{
- XLogRegisterBuffer(6, metabuf, REGBUF_STANDARD);
- XLogRegisterBufData(6, &metap->hashm_firstfree, sizeof(uint32));
+ XLogRegisterBuffer(5, metabuf, REGBUF_STANDARD);
+ XLogRegisterBufData(5, &metap->hashm_firstfree, sizeof(uint32));
}
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SQUEEZE_PAGE);
@@ -966,10 +953,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -998,25 +987,22 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, itup_offsets,
nitups * sizeof(OffsetNumber));
for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
- XLogRegisterBuffer(2, rbuf, REGBUF_STANDARD);
- XLogRegisterBufData(2, deletable,
+ XLogRegisterBuffer(1, rbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_MOVE_PAGE_CONTENTS);
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..0bb0d0590f5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,9 +129,13 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing moved tuples
- * Backup Blk 2: page from which tuples will be removed
+ * Backup Blk 0: page containing moved tuples
+ * Backup Blk 1: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
@@ -149,13 +153,18 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
- * Backup Blk 2: freed overflow page
- * Backup Blk 3: page previous to the freed overflow page
- * Backup Blk 4: page next to the freed overflow page
- * Backup Blk 5: bitmap page containing info of freed overflow page
- * Backup Blk 6: meta page
+ * Backup Blk 0: page containing tuples moved from freed overflow page, if
+ * it is modified
+ * Backup Blk 1: freed overflow page
+ * Backup Blk 2: page previous to the freed overflow page
+ * Backup Blk 3: page next to the freed overflow page
+ * Backup Blk 4: bitmap page containing info of freed overflow page
+ * Backup Blk 5: meta page
+ *
+ * The primary bucket page is registered only as block 0, when it is the
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
@@ -179,8 +188,12 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page from which tuples are deleted
+ * Backup Blk 0: page from which tuples are deleted
+ *
+ * If block 0 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
--
2.47.3
v7-0003-Add-a-recovery-test-for-the-hash-WAL-pin-only-buc.patch (text/x-patch, 11.5K) download
From 31a4b2f750df645949c8e624c29ee2071da538ab Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v7 3/4] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/061_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 +++
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_vacuum_insert_crc.pl | 181 ++++++++++++++++++
3 files changed, 204 insertions(+)
create mode 100644 src/test/recovery/t/061_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index e7ff07ca880..43bf2ef3aa4 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_vacuum_insert_crc.pl',
't/068a_hash_torn_primary_page_delete_first.pl',
't/068b_hash_torn_primary_page_standby.pl',
],
diff --git a/src/test/recovery/t/061_hash_vacuum_insert_crc.pl b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..aa030abd587
--- /dev/null
+++ b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
@@ -0,0 +1,181 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.47.3
v7-0001-Fix-hash-index-redo-reading-a-torn-primary-bucket.patch (text/x-patch, 19.9K) download
From 8423b47a045ee3626be5f4ffd518d55fd5a9afe9 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 12 Nov 2026 12:58:59 +0000
Subject: [PATCH v7 1/4] Fix hash index redo reading a torn primary bucket page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 43 ++++-
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
src/test/recovery/meson.build | 2 +
...68a_hash_torn_primary_page_delete_first.pl | 142 +++++++++++++++
.../t/068b_hash_torn_primary_page_standby.pl | 171 ++++++++++++++++++
6 files changed, 351 insertions(+), 11 deletions(-)
create mode 100644 src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl
create mode 100644 src/test/recovery/t/068b_hash_torn_primary_page_standby.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..e1318bf97db 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -494,10 +495,18 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -621,10 +630,18 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -852,10 +869,18 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..e091a3e178b 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -390,7 +390,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4589,7 +4588,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 8786b6d3a8e..11d3eadef3e 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -216,6 +216,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..e7ff07ca880 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,8 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/068a_hash_torn_primary_page_delete_first.pl',
+ 't/068b_hash_torn_primary_page_standby.pl',
],
},
}
diff --git a/src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl b/src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl
new file mode 100644
index 00000000000..e61a0b98885
--- /dev/null
+++ b/src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl
@@ -0,0 +1,142 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test crash recovery when the primary bucket page of a hash bucket is torn,
+# and the full-page image that repairs it comes after the record that reads it.
+#
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$node->start;
+
+is($node->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $redo = $node->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# The entries of ids 451-600 are on the overflow page, those of ids 1-50 on the
+# primary page. The DELETE for the overflow page comes first; the VACUUM of
+# the primary page then changes it for the first time since the checkpoint, so
+# its record carries the full-page image of the page.
+$node->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$node->safe_psql('postgres', 'VACUUM t');
+$node->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$node->safe_psql('postgres', 'VACUUM t');
+
+my $relpath = $node->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $node->safe_psql('postgres', 'SHOW block_size');
+$node->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# Read the Hash records after the checkpoint.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--rmgr' => 'Hash',
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary bucket page's block number is not a registered block of the
+# overflow-page DELETE (the record carries it only as appended main data), so
+# find it from a record that does register it: a DELETE or SQUEEZE_PAGE marked
+# is_primary T references the primary bucket page as its first block.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #0: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout;
+
+# The overflow-page DELETE (is_primary F) reads the primary bucket page
+# pin-only to take the cleanup lock; it must come before the primary page's
+# first full-page image.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete,
+ 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout;
+
+# Where the first full-page image of the primary page is.
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+$node->stop('immediate');
+
+# Simulate a torn write of the primary page: keep the first half of its block
+# and overwrite the second half.
+if (defined $pblk)
+{
+ my $path = $node->data_dir . '/' . $relpath;
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $started = $node->start(fail_ok => 1);
+ok($started, 'crash recovery succeeds');
+if ($started)
+{
+ is( $node->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'the hash index gives the right result after recovery');
+ $node->stop;
+}
+else
+{
+ my $log = slurp_file($node->logfile);
+ diag("the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
diff --git a/src/test/recovery/t/068b_hash_torn_primary_page_standby.pl b/src/test/recovery/t/068b_hash_torn_primary_page_standby.pl
new file mode 100644
index 00000000000..d9a548a931e
--- /dev/null
+++ b/src/test/recovery/t/068b_hash_torn_primary_page_standby.pl
@@ -0,0 +1,171 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test a standby that starts from a base backup whose copy of the primary
+# bucket page of a hash bucket is torn, and the full-page image that repairs it
+# comes after the record that reads it.
+#
+
+use strict;
+use warnings FATAL => 'all';
+
+use File::Path qw(rmtree);
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1);
+$primary->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$primary->start;
+
+is($primary->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+my $relpath = $primary->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
+
+# Start a low-level backup, which does a checkpoint, and copy the files.
+my $backup_name = 'torn';
+my $backup_dir = $primary->backup_dir . '/' . $backup_name;
+my $psql = $primary->background_psql('postgres');
+$psql->query_safe("SET client_min_messages TO WARNING");
+$psql->set_query_timer_restart;
+$psql->query_safe("select pg_backup_start('torn primary page', true)");
+my $redo = $primary->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
+unlink("$backup_dir/postmaster.pid")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
+unlink("$backup_dir/postmaster.opts")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
+rmtree("$backup_dir/pg_wal")
+ or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
+mkdir("$backup_dir/pg_wal");
+
+# While the backup is in progress: the entries of ids 451-600 are on the
+# overflow page, those of ids 1-50 on the primary page. The DELETE for the
+# overflow page comes first; the VACUUM of the primary page then changes it for
+# the first time since the checkpoint of the backup, so its record carries the
+# full-page image of the page.
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# Read the Hash records after the redo pointer of the backup.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $primary->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--rmgr' => 'Hash',
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
+# block 1, the page that is changed.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #[01]: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout;
+
+# The first DELETE for an overflow page.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete,
+ 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout;
+
+# Where the first full-page image of the primary page is, relative to the
+# DELETE for the overflow page.
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+# The copy of the primary page in the backup is torn: keep the first half of
+# its block and overwrite the second half.
+if (defined $pblk)
+{
+ my $path = "$backup_dir/$relpath";
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+# End the backup, and save backup_label into the backup.
+my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
+$psql->quit;
+open(my $fh, '>', "$backup_dir/backup_label")
+ or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
+print $fh $backup_label;
+close($fh);
+
+# Start a hot standby from the backup. Replay starts at the redo pointer of
+# the backup, replays the DELETE for the overflow page first, and reaches the
+# consistency point only after the end of the backup, after the full-page
+# image of the primary page.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
+$standby->append_conf('postgresql.conf', 'hot_standby = on');
+
+my $started = $standby->start(fail_ok => 1);
+ok($started, 'the standby starts');
+if ($started)
+{
+ $primary->wait_for_catchup($standby);
+ is( $standby->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'the hash index gives the right result on the standby');
+}
+else
+{
+ my $log = slurp_file($standby->logfile);
+ diag("the standby did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.47.3
v7-0004-Remove-REGBUF_NO_CHANGE.patch (text/x-patch, 5.2K) download
From c5f1ab6eab88124df18b46b2d91fab94f78d84f7 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:17:46 -0400
Subject: [PATCH v7 4/4] Remove REGBUF_NO_CHANGE
With the previous commits, the hash index AM no longer registers any
pin-only or otherwise-unchanged buffer, so REGBUF_NO_CHANGE has no users
left. Remove the flag and restore the invariant that every registered
buffer is content-locked and dirty: XLogRegisterBuffer() asserts it
unconditionally again.
This also reverts the defensive measures added in 27caf4ca5ae5, which
let a REGBUF_NO_CHANGE buffer skip the full-page image forced by
wal_consistency_checking: XLogRecordAssemble() no longer special-cases
the flag, and verifyBackupPageConsistency() again asserts that a
registered block carries an image. 27caf4ca5ae5 remains in the back
branches, where this hash rework is not applied.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/transam/README | 5 ----
src/backend/access/transam/xloginsert.c | 28 ++++++-----------------
src/backend/access/transam/xlogrecovery.c | 7 +-----
src/include/access/xloginsert.h | 3 ---
4 files changed, 8 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/transam/README b/src/backend/access/transam/README
index 595afa01fa7..231106270fd 100644
--- a/src/backend/access/transam/README
+++ b/src/backend/access/transam/README
@@ -586,11 +586,6 @@ void XLogRegisterBuffer(uint8 block_id, Buffer buf, uint8 flags);
XLogRegisterBufData() is included in the WAL record even if a full-page
image is taken.
- The REGBUF_NO_CHANGE flag indicates that the buffer is registered without
- being modified by this record, and possibly without an exclusive content
- lock. wal_consistency_checking does not force a full-page image for such
- a buffer.
-
void XLogRegisterData(const void *data, int len);
XLogRegisterData is used to include arbitrary data in the WAL record. If
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index cd3359434e1..2d031e38594 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -257,22 +257,13 @@ XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Assert(begininsert_called);
/*
- * Ordinarily, the buffer should be exclusive-locked (or share-exclusive
- * in case of hint bits) and marked dirty before we get here, otherwise we
- * could end up violating one of the rules in access/transam/README.
- *
- * Some callers intentionally register a clean page and never update that
- * page's LSN; in that case they can pass the flag REGBUF_NO_CHANGE to
- * bypass these checks.
+ * The buffer should be exclusive-locked (or share-exclusive in case of
+ * hint bits) and marked dirty before we get here, otherwise we could end
+ * up violating one of the rules in access/transam/README.
*/
-#ifdef USE_ASSERT_CHECKING
- if (!(flags & REGBUF_NO_CHANGE))
- {
- Assert(BufferIsDirty(buffer));
- Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
- BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
- }
-#endif
+ Assert(BufferIsDirty(buffer));
+ Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
+ BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
if (block_id >= max_registered_block_id)
{
@@ -722,13 +713,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
- *
- * Do not force an image for a REGBUF_NO_CHANGE buffer.
*/
- if (regbuf->flags & REGBUF_NO_CHANGE)
- include_image = needs_backup;
- else
- include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
+ include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index e091a3e178b..1b2c9cc78e9 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2487,12 +2487,7 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- /*
- * Blocks registered with REGBUF_NO_CHANGE may have no image, see
- * XLogRecordAssemble(). Nothing to compare for these.
- */
- if (!XLogRecHasBlockImage(record, block_id))
- continue;
+ Assert(XLogRecHasBlockImage(record, block_id));
if (XLogRecBlockImageApply(record, block_id))
{
diff --git a/src/include/access/xloginsert.h b/src/include/access/xloginsert.h
index 86264564ebb..ddb1a85db59 100644
--- a/src/include/access/xloginsert.h
+++ b/src/include/access/xloginsert.h
@@ -38,9 +38,6 @@
* will be skipped) */
#define REGBUF_KEEP_DATA 0x10 /* include data even if a full-page image
* is taken */
-#define REGBUF_NO_CHANGE 0x20 /* intentionally register clean buffer; no
- * image is forced for WAL consistency
- * checking */
/* prototypes for public functions in xloginsert.c: */
extern void XLogBeginInsert(void);
--
2.47.3
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-12 16:12 ` Joao Rito <joaovictor.rito@gmail.com>
2026-11-13 10:41 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
1 sibling, 1 reply; 34+ messages in thread
From: Joao Rito @ 2026-11-12 16:12 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; +Cc: pgsql-hackers@lists.postgresql.org, vignesh C <vignesh21@gmail.com>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; shihao zhong <zhong950419@gmail.com>
Hi Greg,
Thank you for the v7 patch and the new recovery test.
I tested v7 on a local build. While running 061_hash_vacuum_insert_crc on
Linux (ext4, meson build), subtest 2 failed for me with:
pg_waldump: error: invalid WAL segment size in WAL file
"000000010000000000000002" (0 bytes)
Both LSNs are in segment ...0001, and segment ...0002 is a zero-filled
16 MB file. When --path is a directory, pg_waldump seems to read the
segment size from the first WAL file readdir() returns, so the result
depends on directory order (here 0002 came first).
Passing the segment file for $start_lsn (for example from pg_walfile_name)
worked for me by hand. Subtest 3 passed and I saw no CRC problem. I did
not apply the change to the test and rerun it under meson.
Thanks again!
Regards,
Joao Rito
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 16:12 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Joao Rito <joaovictor.rito@gmail.com>
@ 2026-11-13 10:41 ` vignesh C <vignesh21@gmail.com>
2026-11-13 14:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) João Rito <joaovictor.rito@gmail.com>
0 siblings, 1 reply; 34+ messages in thread
From: vignesh C @ 2026-11-13 10:41 UTC (permalink / raw)
To: Joao Rito <joaovictor.rito@gmail.com>; +Cc: Greg Burd <greg@burd.me>; pgsql-hackers@lists.postgresql.org, Hayato Kuroda <kuroda.hayato@fujitsu.com>; shihao zhong <zhong950419@gmail.com>
On Thu, 12 Nov 2026 at 21:43, Joao Rito <joaovictor.rito@gmail.com> wrote:
>
> Hi Greg,
>
> Thank you for the v7 patch and the new recovery test.
>
> I tested v7 on a local build. While running 061_hash_vacuum_insert_crc on
> Linux (ext4, meson build), subtest 2 failed for me with:y
>
> pg_waldump: error: invalid WAL segment size in WAL file
> "000000010000000000000002" (0 bytes)
>
> Both LSNs are in segment ...0001, and segment ...0002 is a zero-filled
> 16 MB file. When --path is a directory, pg_waldump seems to read the
> segment size from the first WAL file readdir() returns, so the result
> depends on directory order (here 0002 came first).
>
> Passing the segment file for $start_lsn (for example from pg_walfile_name)
> worked for me by hand. Subtest 3 passed and I saw no CRC problem. I did
> not apply the change to the test and rerun it under meson.
Thanks for the comment, this is addressed in the v8 version patch attached.
Apart from that, the following changes were done:
1) prepared back branch patches for the 0001 patch.
2) The test 068 was renamed to the next available 061 test file.
3) Most of the test code was common in
hash_torn_primary_page_delete_first and
hash_torn_primary_page_standby, merged them to a single test
4) the test added along with 0001 was not passing with the first patch
alone, fixed it so that the first patch can be committed separately.
Regards,
Vignesh
Attachments: download all (9 files, .tar.gz)
v8-0001-Fix-hash-index-redo-reading-a-torn-primary-bucket.patch (application/octet-stream, 16.8K) download
From d6babd31b984714950d91988ee2bea0b55131b72 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 12 Nov 2026 12:58:59 +0000
Subject: [PATCH v8 1/4] Fix hash index redo reading a torn primary bucket page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 43 +++-
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_torn_primary_page.pl | 226 ++++++++++++++++++
5 files changed, 263 insertions(+), 11 deletions(-)
create mode 100644 src/test/recovery/t/061_hash_torn_primary_page.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..e1318bf97db 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -494,10 +495,18 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -621,10 +630,18 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -852,10 +869,18 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..e091a3e178b 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -390,7 +390,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4589,7 +4588,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 8786b6d3a8e..11d3eadef3e 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -216,6 +216,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..785f2d820b1 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_torn_primary_page.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
new file mode 100644
index 00000000000..3b71fb409ed
--- /dev/null
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -0,0 +1,226 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test redo of a hash VACUUM record that reads a torn primary bucket page, whose
+# repairing full-page image comes later in the WAL, in a standby started from a
+# base backup and in crash recovery. Data checksums must be on, so that the
+# torn page is detected.
+
+use strict;
+use warnings FATAL => 'all';
+
+use File::Path qw(rmtree);
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+# Tear a block of a relation file, as a torn write does: keep the first half of
+# the block and overwrite the second half with random bytes, so that its
+# checksum does not match.
+sub tear_page
+{
+ my ($path, $pblk, $bs) = @_;
+
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1);
+$primary->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$primary->start;
+
+is($primary->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+my $relpath = $primary->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
+
+# Start a low-level backup, which does a checkpoint, and copy the files.
+my $backup_name = 'torn';
+my $backup_dir = $primary->backup_dir . '/' . $backup_name;
+my $psql = $primary->background_psql('postgres');
+$psql->query_safe("SET client_min_messages TO WARNING");
+$psql->set_query_timer_restart;
+$psql->query_safe("select pg_backup_start('torn primary page', true)");
+my $redo = $primary->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# Copy the data directory of the running server, as a backup does. Remove what
+# must not be in a backup, as pg_basebackup does: postmaster.pid, which would
+# make a server started from the copy think that the primary's postmaster is
+# still running, postmaster.opts, which only records how the primary was
+# started, and the WAL segments, which are copied at an arbitrary moment, and
+# which the standby gets by streaming, starting at the redo pointer of the
+# backup. The server expects pg_wal to exist, so create it empty.
+PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
+unlink("$backup_dir/postmaster.pid")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
+unlink("$backup_dir/postmaster.opts")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
+rmtree("$backup_dir/pg_wal")
+ or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
+mkdir("$backup_dir/pg_wal");
+
+# While the backup is in progress: the entries of ids 451-600 are on the
+# overflow page, those of ids 1-50 on the primary page. The DELETE for the
+# overflow page comes first; the VACUUM of the primary page then changes it for
+# the first time since the checkpoint of the backup, so its record carries the
+# full-page image of the page.
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$primary->safe_psql('postgres', 'VACUUM t');
+
+# Read the Hash records written since the checkpoint.
+my $end_lsn =
+ $primary->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# The first and the last WAL segment of the range.
+my $start_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$redo')");
+my $end_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Dump the Hash records from the redo pointer of the backup to the end of the
+# WAL written so far. The output is parsed below.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $primary->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
+# block 1, the page that is changed.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout, $stderr;
+
+# The DELETE for an overflow page has to come before the first full-page image
+# of the primary page.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete, 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout, $stderr;
+
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout, $stderr;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+# Tear the copy of the primary page in the backup.
+tear_page("$backup_dir/$relpath", $pblk, $bs) if defined $pblk;
+
+# End the backup, and save backup_label into the backup.
+my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
+$psql->quit;
+open(my $fh, '>', "$backup_dir/backup_label")
+ or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
+print $fh $backup_label;
+close($fh);
+
+###############################################################################
+# A standby started from the backup
+###############################################################################
+
+# Replay starts at the redo pointer of the backup, replays the DELETE for the
+# overflow page first, and reaches the consistency point only after the end of
+# the backup, after the full-page image of the primary page.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
+$standby->append_conf('postgresql.conf', 'hot_standby = on');
+
+my $started = $standby->start(fail_ok => 1);
+ok($started, 'standby: the standby starts');
+if ($started)
+{
+ $primary->wait_for_catchup($standby);
+ is( $standby->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'standby: the hash index gives the right result');
+ $standby->stop;
+}
+else
+{
+ my $log = slurp_file($standby->logfile);
+ diag("standby: the standby did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
+}
+
+###############################################################################
+# Crash recovery of the primary
+###############################################################################
+
+# There was no checkpoint since the one of the backup, so crash recovery
+# replays the same records from the same redo pointer. Tear the primary's own
+# copy of the page.
+$primary->stop('immediate');
+tear_page($primary->data_dir . '/' . $relpath, $pblk, $bs) if defined $pblk;
+
+$started = $primary->start(fail_ok => 1);
+ok($started, 'crash recovery: the server starts');
+if ($started)
+{
+ is( $primary->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'crash recovery: the hash index gives the right result');
+}
+else
+{
+ my $log = slurp_file($primary->logfile);
+ diag("crash recovery: the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.55.0
v8-0003-Add-a-recovery-test-for-the-hash-WAL-pin-only-buc.patch (application/octet-stream, 11.7K) download
From c02b634b0d7c5583cab5473b12903f4d7e256bab Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v8 3/4] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/062_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 ++
src/test/recovery/meson.build | 1 +
.../recovery/t/062_hash_vacuum_insert_crc.pl | 191 ++++++++++++++++++
3 files changed, 214 insertions(+)
create mode 100644 src/test/recovery/t/062_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index 785f2d820b1..be397ea20ed 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -70,6 +70,7 @@ tests += {
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
't/061_hash_torn_primary_page.pl',
+ 't/062_hash_vacuum_insert_crc.pl',
],
},
}
diff --git a/src/test/recovery/t/062_hash_vacuum_insert_crc.pl b/src/test/recovery/t/062_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..89f7611af12
--- /dev/null
+++ b/src/test/recovery/t/062_hash_vacuum_insert_crc.pl
@@ -0,0 +1,191 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# The first and the last WAL segment of the range. With only --path, pg_waldump
+# takes the WAL segment size from the first file readdir() returns, which can be
+# a zero-filled, unused segment, and then fails with "invalid WAL segment size".
+# Naming the segments makes it read the size from the first of them.
+my $start_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$start_lsn')");
+my $end_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.55.0
v8-0002-Don-t-register-pin-only-primary-bucket-pages-in-h.patch (application/octet-stream, 24.9K) download
From 6eb46d20b358586a43eecbbb8ad90e85580b4202 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v8 2/4] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that no scan on a hot standby is in progress in the bucket, and
none can start, while tuples are removed or moved. That lock was
obtained by registering the page (pin-only) with REGBUF_NO_CHANGE; redo
never reads data from the block, the registration existed only for the
lock. That broke the rule that a registered buffer is one the caller
holds exclusively locked and dirty, and under wal_consistency_checking
it forced a full-page image of a page a concurrent inserter could still
modify, so the record CRC was computed over shifting data.
Stop registering the primary bucket page when the record does not change
it. When the page is not one of the pages the record changes, the
operation holds only a pin on it, so the record carries the page's block
number in its main data and replay reads that block and takes a cleanup
lock on it directly, at the same point and in the same order as before.
The block number is appended only in that case, so the records are no
larger than before in the common case where the primary bucket page is
registered.
After this change hash registers only buffers it holds exclusively
locked and dirty, and there are no REGBUF_NO_CHANGE users left.
The three record formats change, so bump XLOG_PAGE_MAGIC; master only.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/auNs8b_vS2OPdTL8@floki
---
src/backend/access/hash/README | 9 ++
src/backend/access/hash/hash.c | 17 +--
src/backend/access/hash/hash_xlog.c | 139 ++++++++++--------
src/backend/access/hash/hashovfl.c | 100 ++++++-------
src/include/access/hash_xlog.h | 37 +++--
src/include/access/xlog_internal.h | 2 +-
.../recovery/t/061_hash_torn_primary_page.pl | 6 +-
7 files changed, 169 insertions(+), 141 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record then carries its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..7a79030303e 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -909,19 +909,16 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * If buf is an overflow page, the primary bucket page is not
+ * changed and we hold only a pin on it, so it is not
+ * registered. Append its block number instead, and replay
+ * takes a cleanup lock on it. It is not needed otherwise.
*/
if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
- XLogRegisterBufData(1, deletable,
+ XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_DELETE);
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e1318bf97db..bad5bccb4e1 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -470,6 +470,52 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on the primary bucket page of the bucket that a
+ * squeeze or delete record operates on, when that page is not one of the
+ * pages the record changes and so is not registered in it. Its block number
+ * is stored in the main data of the record, right after the fixed-size struct
+ * of rec_size bytes.
+ *
+ * This serializes replay against scans on a hot standby, which pin the
+ * primary bucket page for their whole duration; see the comments in the
+ * callers. The page is not modified, so nothing is done with it besides
+ * locking it. block_id must be a block of the same index registered in
+ * the record.
+ */
+static Buffer
+hash_xlog_lock_primary_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ BlockNumber bucket_blkno;
+ Buffer buf;
+
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
+ /*
+ * The cleanup lock on the primary bucket page serializes replay against
+ * scans on a hot standby, which pin the page for their whole duration.
+ * Scans can run only once hot standby accepts queries, so until then we
+ * need not read or lock the page. Skipping the read also sidesteps a torn
+ * copy of the page whose repairing full-page image comes later in the WAL:
+ * that hazard exists only before consistency is reached, and queries are
+ * accepted only after that, so once HotStandbyActiveInReplay() is true any
+ * earlier image has already been replayed. Redo never uses the page's
+ * contents here in any case.
+ */
+ if (!HotStandbyActiveInReplay())
+ return InvalidBuffer;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -491,24 +537,12 @@ hash_xlog_move_page_contents(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
- */
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashMovePageContents);
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
}
/* replay the record for adding entries in overflow buffer */
@@ -520,7 +554,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
Size datalen;
uint16 ninserted = 0;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -559,13 +593,13 @@ hash_xlog_move_page_contents(XLogReaderState *record)
}
/* replay the record for deleting entries from overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &deletebuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &deletebuf) == BLK_NEEDS_REDO)
{
Page page;
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 2, &len);
+ ptr = XLogRecGetBlockData(record, 1, &len);
page = BufferGetPage(deletebuf);
@@ -626,25 +660,26 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
- else
{
/*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
+ * If the primary bucket page is modified, it is registered as block
+ * 0 and read for redo. Otherwise, acquire its cleanup lock
+ * separately.
*/
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (XLogRecHasBlockRef(record, 0))
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
+ action = BLK_NOTFOUND;
+ }
+ }
+ else
+ {
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
else
action = BLK_NOTFOUND;
}
@@ -659,7 +694,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint16 ninserted = 0;
bool mod_wbuf = false;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -725,7 +760,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
}
/* replay the record for initializing overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &ovflbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &ovflbuf) == BLK_NEEDS_REDO)
{
Page ovflpage;
HashPageOpaque ovflopaque;
@@ -750,7 +785,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/* replay the record for page previous to the freed overflow page */
if (!xldata->is_prev_bucket_same_wrt &&
- XLogReadBufferForRedo(record, 3, &prevbuf) == BLK_NEEDS_REDO)
+ XLogReadBufferForRedo(record, 2, &prevbuf) == BLK_NEEDS_REDO)
{
Page prevpage = BufferGetPage(prevbuf);
HashPageOpaque prevopaque = HashPageGetOpaque(prevpage);
@@ -764,11 +799,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(prevbuf);
/* replay the record for page next to the freed overflow page */
- if (XLogRecHasBlockRef(record, 4))
+ if (XLogRecHasBlockRef(record, 3))
{
Buffer nextbuf;
- if (XLogReadBufferForRedo(record, 4, &nextbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 3, &nextbuf) == BLK_NEEDS_REDO)
{
Page nextpage = BufferGetPage(nextbuf);
HashPageOpaque nextopaque = HashPageGetOpaque(nextpage);
@@ -795,7 +830,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* index updates can be happening concurrently.
*/
/* replay the record for bitmap page */
- if (XLogReadBufferForRedo(record, 5, &mapbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 4, &mapbuf) == BLK_NEEDS_REDO)
{
Page mappage = BufferGetPage(mapbuf);
uint32 *freep = NULL;
@@ -805,7 +840,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
freep = HashPageGetBitmap(mappage);
- data = XLogRecGetBlockData(record, 5, &datalen);
+ data = XLogRecGetBlockData(record, 4, &datalen);
bitmap_page_bit = (uint32 *) data;
CLRBIT(freep, *bitmap_page_bit);
@@ -817,11 +852,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(mapbuf);
/* replay the record for meta page */
- if (XLogRecHasBlockRef(record, 6))
+ if (XLogRecHasBlockRef(record, 5))
{
Buffer metabuf;
- if (XLogReadBufferForRedo(record, 6, &metabuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 5, &metabuf) == BLK_NEEDS_REDO)
{
HashMetaPage metap;
Page page;
@@ -829,7 +864,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint32 *firstfree_ovflpage;
Size datalen;
- data = XLogRecGetBlockData(record, 6, &datalen);
+ data = XLogRecGetBlockData(record, 5, &datalen);
firstfree_ovflpage = (uint32 *) data;
page = BufferGetPage(metabuf);
@@ -865,24 +900,12 @@ hash_xlog_delete(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_primary_bucket_page)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
- */
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashDelete);
- action = XLogReadBufferForRedo(record, 1, &deletebuf);
+ action = XLogReadBufferForRedo(record, 0, &deletebuf);
}
/* replay the record for deleting entries in bucket page */
@@ -891,7 +914,7 @@ hash_xlog_delete(XLogReaderState *record)
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 1, &len);
+ ptr = XLogRecGetBlockData(record, 0, &len);
page = BufferGetPage(deletebuf);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..7ad934ca38f 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,6 +660,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
@@ -667,45 +672,27 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Register only the pages this record changes. The primary bucket
+ * page is registered only if it is the write page and is modified;
+ * otherwise we may hold only a pin on it, so append its block number
+ * and replay takes a cleanup lock on it.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- if (nitups > 0)
- {
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
+ if (mod_wbuf)
{
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(0, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
+ }
}
- XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(1, ovflbuf, REGBUF_STANDARD);
/*
* If prevpage and the writepage (block in which we are moving tuples
@@ -714,18 +701,18 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* writepage.
*/
if (BufferIsValid(prevbuf) && !is_prev_bucket_same_wrt)
- XLogRegisterBuffer(3, prevbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(2, prevbuf, REGBUF_STANDARD);
if (BufferIsValid(nextbuf))
- XLogRegisterBuffer(4, nextbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(3, nextbuf, REGBUF_STANDARD);
- XLogRegisterBuffer(5, mapbuf, REGBUF_STANDARD);
- XLogRegisterBufData(5, &bitmapbit, sizeof(uint32));
+ XLogRegisterBuffer(4, mapbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(4, &bitmapbit, sizeof(uint32));
if (update_metap)
{
- XLogRegisterBuffer(6, metabuf, REGBUF_STANDARD);
- XLogRegisterBufData(6, &metap->hashm_firstfree, sizeof(uint32));
+ XLogRegisterBuffer(5, metabuf, REGBUF_STANDARD);
+ XLogRegisterBufData(5, &metap->hashm_firstfree, sizeof(uint32));
}
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SQUEEZE_PAGE);
@@ -966,10 +953,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -998,25 +987,22 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, itup_offsets,
nitups * sizeof(OffsetNumber));
for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
- XLogRegisterBuffer(2, rbuf, REGBUF_STANDARD);
- XLogRegisterBufData(2, deletable,
+ XLogRegisterBuffer(1, rbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_MOVE_PAGE_CONTENTS);
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..0bb0d0590f5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,9 +129,13 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing moved tuples
- * Backup Blk 2: page from which tuples will be removed
+ * Backup Blk 0: page containing moved tuples
+ * Backup Blk 1: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
@@ -149,13 +153,18 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
- * Backup Blk 2: freed overflow page
- * Backup Blk 3: page previous to the freed overflow page
- * Backup Blk 4: page next to the freed overflow page
- * Backup Blk 5: bitmap page containing info of freed overflow page
- * Backup Blk 6: meta page
+ * Backup Blk 0: page containing tuples moved from freed overflow page, if
+ * it is modified
+ * Backup Blk 1: freed overflow page
+ * Backup Blk 2: page previous to the freed overflow page
+ * Backup Blk 3: page next to the freed overflow page
+ * Backup Blk 4: bitmap page containing info of freed overflow page
+ * Backup Blk 5: meta page
+ *
+ * The primary bucket page is registered only as block 0, when it is the
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
@@ -179,8 +188,12 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page from which tuples are deleted
+ * Backup Blk 0: page from which tuples are deleted
+ *
+ * If block 0 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
index 3b71fb409ed..eaf3747f04c 100644
--- a/src/test/recovery/t/061_hash_torn_primary_page.pl
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -117,13 +117,13 @@ IPC::Run::run(
'2>' => \$stderr);
my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
-# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
-# block 1, the page that is changed.
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T changes it, so
+# it is the first block reference of the record.
my $pblk;
for my $r (@records)
{
if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
- && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ && $r =~ /blkref #0: rel \S+ blk (\d+)/)
{
$pblk = $1;
last;
--
2.55.0
v8-0004-Remove-REGBUF_NO_CHANGE.patch (application/octet-stream, 5.1K) download
From 058d2078a40d5041ab3792045b2c6c164dc2eccf Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:17:46 -0400
Subject: [PATCH v8 4/4] Remove REGBUF_NO_CHANGE
With the previous commits, the hash index AM no longer registers any
pin-only or otherwise-unchanged buffer, so REGBUF_NO_CHANGE has no users
left. Remove the flag and restore the invariant that every registered
buffer is content-locked and dirty: XLogRegisterBuffer() asserts it
unconditionally again.
This also reverts the defensive measures added in 27caf4ca5ae5, which
let a REGBUF_NO_CHANGE buffer skip the full-page image forced by
wal_consistency_checking: XLogRecordAssemble() no longer special-cases
the flag, and verifyBackupPageConsistency() again asserts that a
registered block carries an image. 27caf4ca5ae5 remains in the back
branches, where this hash rework is not applied.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/transam/README | 5 ----
src/backend/access/transam/xloginsert.c | 28 ++++++-----------------
src/backend/access/transam/xlogrecovery.c | 7 +-----
src/include/access/xloginsert.h | 3 ---
4 files changed, 8 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/transam/README b/src/backend/access/transam/README
index 595afa01fa7..231106270fd 100644
--- a/src/backend/access/transam/README
+++ b/src/backend/access/transam/README
@@ -586,11 +586,6 @@ void XLogRegisterBuffer(uint8 block_id, Buffer buf, uint8 flags);
XLogRegisterBufData() is included in the WAL record even if a full-page
image is taken.
- The REGBUF_NO_CHANGE flag indicates that the buffer is registered without
- being modified by this record, and possibly without an exclusive content
- lock. wal_consistency_checking does not force a full-page image for such
- a buffer.
-
void XLogRegisterData(const void *data, int len);
XLogRegisterData is used to include arbitrary data in the WAL record. If
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index cd3359434e1..2d031e38594 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -257,22 +257,13 @@ XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Assert(begininsert_called);
/*
- * Ordinarily, the buffer should be exclusive-locked (or share-exclusive
- * in case of hint bits) and marked dirty before we get here, otherwise we
- * could end up violating one of the rules in access/transam/README.
- *
- * Some callers intentionally register a clean page and never update that
- * page's LSN; in that case they can pass the flag REGBUF_NO_CHANGE to
- * bypass these checks.
+ * The buffer should be exclusive-locked (or share-exclusive in case of
+ * hint bits) and marked dirty before we get here, otherwise we could end
+ * up violating one of the rules in access/transam/README.
*/
-#ifdef USE_ASSERT_CHECKING
- if (!(flags & REGBUF_NO_CHANGE))
- {
- Assert(BufferIsDirty(buffer));
- Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
- BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
- }
-#endif
+ Assert(BufferIsDirty(buffer));
+ Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
+ BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
if (block_id >= max_registered_block_id)
{
@@ -722,13 +713,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
- *
- * Do not force an image for a REGBUF_NO_CHANGE buffer.
*/
- if (regbuf->flags & REGBUF_NO_CHANGE)
- include_image = needs_backup;
- else
- include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
+ include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index e091a3e178b..1b2c9cc78e9 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2487,12 +2487,7 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- /*
- * Blocks registered with REGBUF_NO_CHANGE may have no image, see
- * XLogRecordAssemble(). Nothing to compare for these.
- */
- if (!XLogRecHasBlockImage(record, block_id))
- continue;
+ Assert(XLogRecHasBlockImage(record, block_id));
if (XLogRecBlockImageApply(record, block_id))
{
diff --git a/src/include/access/xloginsert.h b/src/include/access/xloginsert.h
index 86264564ebb..ddb1a85db59 100644
--- a/src/include/access/xloginsert.h
+++ b/src/include/access/xloginsert.h
@@ -38,9 +38,6 @@
* will be skipped) */
#define REGBUF_KEEP_DATA 0x10 /* include data even if a full-page image
* is taken */
-#define REGBUF_NO_CHANGE 0x20 /* intentionally register clean buffer; no
- * image is forced for WAL consistency
- * checking */
/* prototypes for public functions in xloginsert.c: */
extern void XLogBeginInsert(void);
--
2.55.0
v8_REL15-0001-Fix-hash-index-redo-reading-a-torn-primary-.patch (application/octet-stream, 16.3K) download
From f051025aa9a976e54326b0de67852ec337757746 Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Fri, 13 Nov 2026 14:31:36 +0530
Subject: [PATCH v8_REL15] Fix hash index redo reading a torn primary bucket
page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 43 +++-
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
.../recovery/t/061_hash_torn_primary_page.pl | 226 ++++++++++++++++++
4 files changed, 262 insertions(+), 11 deletions(-)
create mode 100644 src/test/recovery/t/061_hash_torn_primary_page.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e541ce81ce6..b94c0269d4d 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -19,6 +19,7 @@
#include "access/hash_xlog.h"
#include "access/transam.h"
#include "access/xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "miscadmin.h"
#include "storage/procarray.h"
@@ -500,10 +501,18 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -628,10 +637,18 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -840,10 +857,18 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index a853bbb8d19..68e78f867a1 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -439,7 +439,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, int emode, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4578,7 +4577,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 55ccbe23f0b..d3a567d15de 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -135,6 +135,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
new file mode 100644
index 00000000000..592462048cd
--- /dev/null
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -0,0 +1,226 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test redo of a hash VACUUM record that reads a torn primary bucket page, whose
+# repairing full-page image comes later in the WAL, in a standby started from a
+# base backup and in crash recovery. Data checksums must be on, so that the
+# torn page is detected.
+
+use strict;
+use warnings FATAL => 'all';
+
+use File::Path qw(rmtree);
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+# Tear a block of a relation file, as a torn write does: keep the first half of
+# the block and overwrite the second half with random bytes, so that its
+# checksum does not match.
+sub tear_page
+{
+ my ($path, $pblk, $bs) = @_;
+
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1, extra => ['--data-checksums']);
+$primary->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$primary->start;
+
+is($primary->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+my $relpath = $primary->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
+
+# Start a low-level backup, which does a checkpoint, and copy the files.
+my $backup_name = 'torn';
+my $backup_dir = $primary->backup_dir . '/' . $backup_name;
+my $psql = $primary->background_psql('postgres');
+$psql->query_safe("SET client_min_messages TO WARNING");
+$psql->set_query_timer_restart;
+$psql->query_safe("select pg_backup_start('torn primary page', true)");
+my $redo = $primary->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# Copy the data directory of the running server, as a backup does. Remove what
+# must not be in a backup, as pg_basebackup does: postmaster.pid, which would
+# make a server started from the copy think that the primary's postmaster is
+# still running, postmaster.opts, which only records how the primary was
+# started, and the WAL segments, which are copied at an arbitrary moment, and
+# which the standby gets by streaming, starting at the redo pointer of the
+# backup. The server expects pg_wal to exist, so create it empty.
+PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
+unlink("$backup_dir/postmaster.pid")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
+unlink("$backup_dir/postmaster.opts")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
+rmtree("$backup_dir/pg_wal")
+ or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
+mkdir("$backup_dir/pg_wal");
+
+# While the backup is in progress: the entries of ids 451-600 are on the
+# overflow page, those of ids 1-50 on the primary page. The DELETE for the
+# overflow page comes first; the VACUUM of the primary page then changes it for
+# the first time since the checkpoint of the backup, so its record carries the
+# full-page image of the page.
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$primary->safe_psql('postgres', 'VACUUM t');
+
+# Read the Hash records written since the checkpoint.
+my $end_lsn =
+ $primary->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# The first and the last WAL segment of the range.
+my $start_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$redo')");
+my $end_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Dump the Hash records from the redo pointer of the backup to the end of the
+# WAL written so far. The output is parsed below.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $primary->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
+# block 1, the page that is changed.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout, $stderr;
+
+# The DELETE for an overflow page has to come before the first full-page image
+# of the primary page.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete, 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout, $stderr;
+
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout, $stderr;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+# Tear the copy of the primary page in the backup.
+tear_page("$backup_dir/$relpath", $pblk, $bs) if defined $pblk;
+
+# End the backup, and save backup_label into the backup.
+my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
+$psql->quit;
+open(my $fh, '>', "$backup_dir/backup_label")
+ or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
+print $fh $backup_label;
+close($fh);
+
+###############################################################################
+# A standby started from the backup
+###############################################################################
+
+# Replay starts at the redo pointer of the backup, replays the DELETE for the
+# overflow page first, and reaches the consistency point only after the end of
+# the backup, after the full-page image of the primary page.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
+$standby->append_conf('postgresql.conf', 'hot_standby = on');
+
+my $started = $standby->start(fail_ok => 1);
+ok($started, 'standby: the standby starts');
+if ($started)
+{
+ $primary->wait_for_catchup($standby);
+ is( $standby->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'standby: the hash index gives the right result');
+ $standby->stop;
+}
+else
+{
+ my $log = slurp_file($standby->logfile);
+ diag("standby: the standby did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
+}
+
+###############################################################################
+# Crash recovery of the primary
+###############################################################################
+
+# There was no checkpoint since the one of the backup, so crash recovery
+# replays the same records from the same redo pointer. Tear the primary's own
+# copy of the page.
+$primary->stop('immediate');
+tear_page($primary->data_dir . '/' . $relpath, $pblk, $bs) if defined $pblk;
+
+$started = $primary->start(fail_ok => 1);
+ok($started, 'crash recovery: the server starts');
+if ($started)
+{
+ is( $primary->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'crash recovery: the hash index gives the right result');
+}
+else
+{
+ my $log = slurp_file($primary->logfile);
+ diag("crash recovery: the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.55.0
v8_REL17-0001-Fix-hash-index-redo-reading-a-torn-primary-.patch (application/octet-stream, 16.8K) download
From a5aaf0f2208a3d8ff53039e21fe756c2c7f3eab7 Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Fri, 13 Nov 2026 12:58:16 +0530
Subject: [PATCH v8_REL17] Fix hash index redo reading a torn primary bucket
page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 43 +++-
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_torn_primary_page.pl | 226 ++++++++++++++++++
5 files changed, 263 insertions(+), 11 deletions(-)
create mode 100644 src/test/recovery/t/061_hash_torn_primary_page.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index de88697f191..52f19ab2688 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -496,10 +497,18 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -624,10 +633,18 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -856,10 +873,18 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 1ae2320a29f..d842c3fedc5 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -441,7 +441,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, int emode, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4583,7 +4582,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 8d1a1277fbc..f86e11f3d5b 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -136,6 +136,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index d0f6b848b2e..76c843f86a3 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -61,6 +61,7 @@ tests += {
't/055_cascade_reconnect.pl',
't/056_standby_snapshot_export.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_torn_primary_page.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
new file mode 100644
index 00000000000..592462048cd
--- /dev/null
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -0,0 +1,226 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test redo of a hash VACUUM record that reads a torn primary bucket page, whose
+# repairing full-page image comes later in the WAL, in a standby started from a
+# base backup and in crash recovery. Data checksums must be on, so that the
+# torn page is detected.
+
+use strict;
+use warnings FATAL => 'all';
+
+use File::Path qw(rmtree);
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+# Tear a block of a relation file, as a torn write does: keep the first half of
+# the block and overwrite the second half with random bytes, so that its
+# checksum does not match.
+sub tear_page
+{
+ my ($path, $pblk, $bs) = @_;
+
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1, extra => ['--data-checksums']);
+$primary->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$primary->start;
+
+is($primary->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+my $relpath = $primary->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
+
+# Start a low-level backup, which does a checkpoint, and copy the files.
+my $backup_name = 'torn';
+my $backup_dir = $primary->backup_dir . '/' . $backup_name;
+my $psql = $primary->background_psql('postgres');
+$psql->query_safe("SET client_min_messages TO WARNING");
+$psql->set_query_timer_restart;
+$psql->query_safe("select pg_backup_start('torn primary page', true)");
+my $redo = $primary->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# Copy the data directory of the running server, as a backup does. Remove what
+# must not be in a backup, as pg_basebackup does: postmaster.pid, which would
+# make a server started from the copy think that the primary's postmaster is
+# still running, postmaster.opts, which only records how the primary was
+# started, and the WAL segments, which are copied at an arbitrary moment, and
+# which the standby gets by streaming, starting at the redo pointer of the
+# backup. The server expects pg_wal to exist, so create it empty.
+PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
+unlink("$backup_dir/postmaster.pid")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
+unlink("$backup_dir/postmaster.opts")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
+rmtree("$backup_dir/pg_wal")
+ or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
+mkdir("$backup_dir/pg_wal");
+
+# While the backup is in progress: the entries of ids 451-600 are on the
+# overflow page, those of ids 1-50 on the primary page. The DELETE for the
+# overflow page comes first; the VACUUM of the primary page then changes it for
+# the first time since the checkpoint of the backup, so its record carries the
+# full-page image of the page.
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$primary->safe_psql('postgres', 'VACUUM t');
+
+# Read the Hash records written since the checkpoint.
+my $end_lsn =
+ $primary->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# The first and the last WAL segment of the range.
+my $start_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$redo')");
+my $end_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Dump the Hash records from the redo pointer of the backup to the end of the
+# WAL written so far. The output is parsed below.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $primary->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
+# block 1, the page that is changed.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout, $stderr;
+
+# The DELETE for an overflow page has to come before the first full-page image
+# of the primary page.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete, 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout, $stderr;
+
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout, $stderr;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+# Tear the copy of the primary page in the backup.
+tear_page("$backup_dir/$relpath", $pblk, $bs) if defined $pblk;
+
+# End the backup, and save backup_label into the backup.
+my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
+$psql->quit;
+open(my $fh, '>', "$backup_dir/backup_label")
+ or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
+print $fh $backup_label;
+close($fh);
+
+###############################################################################
+# A standby started from the backup
+###############################################################################
+
+# Replay starts at the redo pointer of the backup, replays the DELETE for the
+# overflow page first, and reaches the consistency point only after the end of
+# the backup, after the full-page image of the primary page.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
+$standby->append_conf('postgresql.conf', 'hot_standby = on');
+
+my $started = $standby->start(fail_ok => 1);
+ok($started, 'standby: the standby starts');
+if ($started)
+{
+ $primary->wait_for_catchup($standby);
+ is( $standby->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'standby: the hash index gives the right result');
+ $standby->stop;
+}
+else
+{
+ my $log = slurp_file($standby->logfile);
+ diag("standby: the standby did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
+}
+
+###############################################################################
+# Crash recovery of the primary
+###############################################################################
+
+# There was no checkpoint since the one of the backup, so crash recovery
+# replays the same records from the same redo pointer. Tear the primary's own
+# copy of the page.
+$primary->stop('immediate');
+tear_page($primary->data_dir . '/' . $relpath, $pblk, $bs) if defined $pblk;
+
+$started = $primary->start(fail_ok => 1);
+ok($started, 'crash recovery: the server starts');
+if ($started)
+{
+ is( $primary->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'crash recovery: the hash index gives the right result');
+}
+else
+{
+ my $log = slurp_file($primary->logfile);
+ diag("crash recovery: the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.55.0
v8_REL19-0001-Fix-hash-index-redo-reading-a-torn-primary-.patch (application/octet-stream, 16.8K) download
From 9898ef3603298d12c6c5156980fd0642e6ffa081 Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Fri, 13 Nov 2026 12:37:56 +0530
Subject: [PATCH v8_REL19] Fix hash index redo reading a torn primary bucket
page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 43 +++-
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_torn_primary_page.pl | 226 ++++++++++++++++++
5 files changed, 263 insertions(+), 11 deletions(-)
create mode 100644 src/test/recovery/t/061_hash_torn_primary_page.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..e1318bf97db 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -494,10 +495,18 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -621,10 +630,18 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -852,10 +869,18 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 3ef42087887..aabc1c3d248 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -388,7 +388,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4575,7 +4574,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 261d11670dc..16fcd4ac7a8 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -216,6 +216,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index 87dbdb6326e..9ca48c27a67 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -68,6 +68,7 @@ tests += {
't/057_snapshot_commit_race.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_torn_primary_page.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
new file mode 100644
index 00000000000..3b71fb409ed
--- /dev/null
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -0,0 +1,226 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test redo of a hash VACUUM record that reads a torn primary bucket page, whose
+# repairing full-page image comes later in the WAL, in a standby started from a
+# base backup and in crash recovery. Data checksums must be on, so that the
+# torn page is detected.
+
+use strict;
+use warnings FATAL => 'all';
+
+use File::Path qw(rmtree);
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+# Tear a block of a relation file, as a torn write does: keep the first half of
+# the block and overwrite the second half with random bytes, so that its
+# checksum does not match.
+sub tear_page
+{
+ my ($path, $pblk, $bs) = @_;
+
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1);
+$primary->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$primary->start;
+
+is($primary->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+my $relpath = $primary->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
+
+# Start a low-level backup, which does a checkpoint, and copy the files.
+my $backup_name = 'torn';
+my $backup_dir = $primary->backup_dir . '/' . $backup_name;
+my $psql = $primary->background_psql('postgres');
+$psql->query_safe("SET client_min_messages TO WARNING");
+$psql->set_query_timer_restart;
+$psql->query_safe("select pg_backup_start('torn primary page', true)");
+my $redo = $primary->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# Copy the data directory of the running server, as a backup does. Remove what
+# must not be in a backup, as pg_basebackup does: postmaster.pid, which would
+# make a server started from the copy think that the primary's postmaster is
+# still running, postmaster.opts, which only records how the primary was
+# started, and the WAL segments, which are copied at an arbitrary moment, and
+# which the standby gets by streaming, starting at the redo pointer of the
+# backup. The server expects pg_wal to exist, so create it empty.
+PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
+unlink("$backup_dir/postmaster.pid")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
+unlink("$backup_dir/postmaster.opts")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
+rmtree("$backup_dir/pg_wal")
+ or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
+mkdir("$backup_dir/pg_wal");
+
+# While the backup is in progress: the entries of ids 451-600 are on the
+# overflow page, those of ids 1-50 on the primary page. The DELETE for the
+# overflow page comes first; the VACUUM of the primary page then changes it for
+# the first time since the checkpoint of the backup, so its record carries the
+# full-page image of the page.
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$primary->safe_psql('postgres', 'VACUUM t');
+
+# Read the Hash records written since the checkpoint.
+my $end_lsn =
+ $primary->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# The first and the last WAL segment of the range.
+my $start_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$redo')");
+my $end_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Dump the Hash records from the redo pointer of the backup to the end of the
+# WAL written so far. The output is parsed below.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $primary->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
+# block 1, the page that is changed.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout, $stderr;
+
+# The DELETE for an overflow page has to come before the first full-page image
+# of the primary page.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete, 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout, $stderr;
+
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout, $stderr;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+# Tear the copy of the primary page in the backup.
+tear_page("$backup_dir/$relpath", $pblk, $bs) if defined $pblk;
+
+# End the backup, and save backup_label into the backup.
+my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
+$psql->quit;
+open(my $fh, '>', "$backup_dir/backup_label")
+ or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
+print $fh $backup_label;
+close($fh);
+
+###############################################################################
+# A standby started from the backup
+###############################################################################
+
+# Replay starts at the redo pointer of the backup, replays the DELETE for the
+# overflow page first, and reaches the consistency point only after the end of
+# the backup, after the full-page image of the primary page.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
+$standby->append_conf('postgresql.conf', 'hot_standby = on');
+
+my $started = $standby->start(fail_ok => 1);
+ok($started, 'standby: the standby starts');
+if ($started)
+{
+ $primary->wait_for_catchup($standby);
+ is( $standby->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'standby: the hash index gives the right result');
+ $standby->stop;
+}
+else
+{
+ my $log = slurp_file($standby->logfile);
+ diag("standby: the standby did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
+}
+
+###############################################################################
+# Crash recovery of the primary
+###############################################################################
+
+# There was no checkpoint since the one of the backup, so crash recovery
+# replays the same records from the same redo pointer. Tear the primary's own
+# copy of the page.
+$primary->stop('immediate');
+tear_page($primary->data_dir . '/' . $relpath, $pblk, $bs) if defined $pblk;
+
+$started = $primary->start(fail_ok => 1);
+ok($started, 'crash recovery: the server starts');
+if ($started)
+{
+ is( $primary->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'crash recovery: the hash index gives the right result');
+}
+else
+{
+ my $log = slurp_file($primary->logfile);
+ diag("crash recovery: the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.55.0
v8_REL16-0001-Fix-hash-index-redo-reading-a-torn-primary-.patch (application/octet-stream, 16.8K) download
From 43149b78b4869ce7948ab8e55431ec7590d318f0 Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Fri, 13 Nov 2026 14:11:28 +0530
Subject: [PATCH v8_REL16] Fix hash index redo reading a torn primary bucket
page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 43 +++-
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_torn_primary_page.pl | 226 ++++++++++++++++++
5 files changed, 263 insertions(+), 11 deletions(-)
create mode 100644 src/test/recovery/t/061_hash_torn_primary_page.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index cd9617533c2..09477ac431c 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -19,6 +19,7 @@
#include "access/hash_xlog.h"
#include "access/transam.h"
#include "access/xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "miscadmin.h"
#include "storage/procarray.h"
@@ -499,10 +500,18 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -627,10 +636,18 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -839,10 +856,18 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 2bc615a691b..7f9ec6d8075 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -441,7 +441,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, int emode, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4528,7 +4527,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 7737f9e2cf0..0c25471c2e5 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -136,6 +136,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index 172e9c7b0f9..fcfeda10c63 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -51,6 +51,7 @@ tests += {
't/055_cascade_reconnect.pl',
't/056_standby_snapshot_export.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_torn_primary_page.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
new file mode 100644
index 00000000000..592462048cd
--- /dev/null
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -0,0 +1,226 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test redo of a hash VACUUM record that reads a torn primary bucket page, whose
+# repairing full-page image comes later in the WAL, in a standby started from a
+# base backup and in crash recovery. Data checksums must be on, so that the
+# torn page is detected.
+
+use strict;
+use warnings FATAL => 'all';
+
+use File::Path qw(rmtree);
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+# Tear a block of a relation file, as a torn write does: keep the first half of
+# the block and overwrite the second half with random bytes, so that its
+# checksum does not match.
+sub tear_page
+{
+ my ($path, $pblk, $bs) = @_;
+
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1, extra => ['--data-checksums']);
+$primary->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$primary->start;
+
+is($primary->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+my $relpath = $primary->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
+
+# Start a low-level backup, which does a checkpoint, and copy the files.
+my $backup_name = 'torn';
+my $backup_dir = $primary->backup_dir . '/' . $backup_name;
+my $psql = $primary->background_psql('postgres');
+$psql->query_safe("SET client_min_messages TO WARNING");
+$psql->set_query_timer_restart;
+$psql->query_safe("select pg_backup_start('torn primary page', true)");
+my $redo = $primary->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# Copy the data directory of the running server, as a backup does. Remove what
+# must not be in a backup, as pg_basebackup does: postmaster.pid, which would
+# make a server started from the copy think that the primary's postmaster is
+# still running, postmaster.opts, which only records how the primary was
+# started, and the WAL segments, which are copied at an arbitrary moment, and
+# which the standby gets by streaming, starting at the redo pointer of the
+# backup. The server expects pg_wal to exist, so create it empty.
+PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
+unlink("$backup_dir/postmaster.pid")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
+unlink("$backup_dir/postmaster.opts")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
+rmtree("$backup_dir/pg_wal")
+ or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
+mkdir("$backup_dir/pg_wal");
+
+# While the backup is in progress: the entries of ids 451-600 are on the
+# overflow page, those of ids 1-50 on the primary page. The DELETE for the
+# overflow page comes first; the VACUUM of the primary page then changes it for
+# the first time since the checkpoint of the backup, so its record carries the
+# full-page image of the page.
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$primary->safe_psql('postgres', 'VACUUM t');
+
+# Read the Hash records written since the checkpoint.
+my $end_lsn =
+ $primary->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# The first and the last WAL segment of the range.
+my $start_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$redo')");
+my $end_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Dump the Hash records from the redo pointer of the backup to the end of the
+# WAL written so far. The output is parsed below.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $primary->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
+# block 1, the page that is changed.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout, $stderr;
+
+# The DELETE for an overflow page has to come before the first full-page image
+# of the primary page.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete, 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout, $stderr;
+
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout, $stderr;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+# Tear the copy of the primary page in the backup.
+tear_page("$backup_dir/$relpath", $pblk, $bs) if defined $pblk;
+
+# End the backup, and save backup_label into the backup.
+my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
+$psql->quit;
+open(my $fh, '>', "$backup_dir/backup_label")
+ or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
+print $fh $backup_label;
+close($fh);
+
+###############################################################################
+# A standby started from the backup
+###############################################################################
+
+# Replay starts at the redo pointer of the backup, replays the DELETE for the
+# overflow page first, and reaches the consistency point only after the end of
+# the backup, after the full-page image of the primary page.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
+$standby->append_conf('postgresql.conf', 'hot_standby = on');
+
+my $started = $standby->start(fail_ok => 1);
+ok($started, 'standby: the standby starts');
+if ($started)
+{
+ $primary->wait_for_catchup($standby);
+ is( $standby->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'standby: the hash index gives the right result');
+ $standby->stop;
+}
+else
+{
+ my $log = slurp_file($standby->logfile);
+ diag("standby: the standby did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
+}
+
+###############################################################################
+# Crash recovery of the primary
+###############################################################################
+
+# There was no checkpoint since the one of the backup, so crash recovery
+# replays the same records from the same redo pointer. Tear the primary's own
+# copy of the page.
+$primary->stop('immediate');
+tear_page($primary->data_dir . '/' . $relpath, $pblk, $bs) if defined $pblk;
+
+$started = $primary->start(fail_ok => 1);
+ok($started, 'crash recovery: the server starts');
+if ($started)
+{
+ is( $primary->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'crash recovery: the hash index gives the right result');
+}
+else
+{
+ my $log = slurp_file($primary->logfile);
+ diag("crash recovery: the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.55.0
v8_REL18-0001-Fix-hash-index-redo-reading-a-torn-primary-.patch (application/octet-stream, 16.8K) download
From 58f0af3c9cc21cc8677ca8d08cd4db6dfcd280f6 Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Fri, 13 Nov 2026 12:48:17 +0530
Subject: [PATCH v8_REL18] Fix hash index redo reading a torn primary bucket
page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 43 +++-
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_torn_primary_page.pl | 226 ++++++++++++++++++
5 files changed, 263 insertions(+), 11 deletions(-)
create mode 100644 src/test/recovery/t/061_hash_torn_primary_page.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index d4cb6246b48..8a5bc4379e6 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -496,10 +497,18 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -624,10 +633,18 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -856,10 +873,18 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 0b2d4eca001..c884e6c5ac5 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -448,7 +448,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4614,7 +4613,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 771ff1ea23a..0f1648d584f 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -136,6 +136,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index cbd701891ed..40479537861 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -63,6 +63,7 @@ tests += {
't/056_standby_snapshot_export.pl',
't/057_snapshot_commit_race.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_torn_primary_page.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
new file mode 100644
index 00000000000..3b71fb409ed
--- /dev/null
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -0,0 +1,226 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test redo of a hash VACUUM record that reads a torn primary bucket page, whose
+# repairing full-page image comes later in the WAL, in a standby started from a
+# base backup and in crash recovery. Data checksums must be on, so that the
+# torn page is detected.
+
+use strict;
+use warnings FATAL => 'all';
+
+use File::Path qw(rmtree);
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+# Tear a block of a relation file, as a torn write does: keep the first half of
+# the block and overwrite the second half with random bytes, so that its
+# checksum does not match.
+sub tear_page
+{
+ my ($path, $pblk, $bs) = @_;
+
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1);
+$primary->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$primary->start;
+
+is($primary->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+my $relpath = $primary->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
+
+# Start a low-level backup, which does a checkpoint, and copy the files.
+my $backup_name = 'torn';
+my $backup_dir = $primary->backup_dir . '/' . $backup_name;
+my $psql = $primary->background_psql('postgres');
+$psql->query_safe("SET client_min_messages TO WARNING");
+$psql->set_query_timer_restart;
+$psql->query_safe("select pg_backup_start('torn primary page', true)");
+my $redo = $primary->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# Copy the data directory of the running server, as a backup does. Remove what
+# must not be in a backup, as pg_basebackup does: postmaster.pid, which would
+# make a server started from the copy think that the primary's postmaster is
+# still running, postmaster.opts, which only records how the primary was
+# started, and the WAL segments, which are copied at an arbitrary moment, and
+# which the standby gets by streaming, starting at the redo pointer of the
+# backup. The server expects pg_wal to exist, so create it empty.
+PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
+unlink("$backup_dir/postmaster.pid")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
+unlink("$backup_dir/postmaster.opts")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
+rmtree("$backup_dir/pg_wal")
+ or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
+mkdir("$backup_dir/pg_wal");
+
+# While the backup is in progress: the entries of ids 451-600 are on the
+# overflow page, those of ids 1-50 on the primary page. The DELETE for the
+# overflow page comes first; the VACUUM of the primary page then changes it for
+# the first time since the checkpoint of the backup, so its record carries the
+# full-page image of the page.
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$primary->safe_psql('postgres', 'VACUUM t');
+
+# Read the Hash records written since the checkpoint.
+my $end_lsn =
+ $primary->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# The first and the last WAL segment of the range.
+my $start_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$redo')");
+my $end_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Dump the Hash records from the redo pointer of the backup to the end of the
+# WAL written so far. The output is parsed below.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $primary->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
+# block 1, the page that is changed.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout, $stderr;
+
+# The DELETE for an overflow page has to come before the first full-page image
+# of the primary page.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete, 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout, $stderr;
+
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout, $stderr;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+# Tear the copy of the primary page in the backup.
+tear_page("$backup_dir/$relpath", $pblk, $bs) if defined $pblk;
+
+# End the backup, and save backup_label into the backup.
+my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
+$psql->quit;
+open(my $fh, '>', "$backup_dir/backup_label")
+ or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
+print $fh $backup_label;
+close($fh);
+
+###############################################################################
+# A standby started from the backup
+###############################################################################
+
+# Replay starts at the redo pointer of the backup, replays the DELETE for the
+# overflow page first, and reaches the consistency point only after the end of
+# the backup, after the full-page image of the primary page.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
+$standby->append_conf('postgresql.conf', 'hot_standby = on');
+
+my $started = $standby->start(fail_ok => 1);
+ok($started, 'standby: the standby starts');
+if ($started)
+{
+ $primary->wait_for_catchup($standby);
+ is( $standby->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'standby: the hash index gives the right result');
+ $standby->stop;
+}
+else
+{
+ my $log = slurp_file($standby->logfile);
+ diag("standby: the standby did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
+}
+
+###############################################################################
+# Crash recovery of the primary
+###############################################################################
+
+# There was no checkpoint since the one of the backup, so crash recovery
+# replays the same records from the same redo pointer. Tear the primary's own
+# copy of the page.
+$primary->stop('immediate');
+tear_page($primary->data_dir . '/' . $relpath, $pblk, $bs) if defined $pblk;
+
+$started = $primary->start(fail_ok => 1);
+ok($started, 'crash recovery: the server starts');
+if ($started)
+{
+ is( $primary->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'crash recovery: the hash index gives the right result');
+}
+else
+{
+ my $log = slurp_file($primary->logfile);
+ diag("crash recovery: the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.55.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 16:12 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Joao Rito <joaovictor.rito@gmail.com>
2026-11-13 10:41 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
@ 2026-11-13 14:48 ` João Rito <joaovictor.rito@gmail.com>
0 siblings, 0 replies; 34+ messages in thread
From: João Rito @ 2026-11-13 14:48 UTC (permalink / raw)
To: vignesh C <vignesh21@gmail.com>; +Cc: Greg Burd <greg@burd.me>; pgsql-hackers@lists.postgresql.org, Hayato Kuroda <kuroda.hayato@fujitsu.com>; shihao zhong <zhong950419@gmail.com>
Hi Vignesh, Greg,
Thank you for v8, and for fixing the pg_waldump segment size problem I
hit with v7.
I tested v8-0001..0004 applied in order on current master
(77bba5454f), with cassert and injection points enabled (meson, Debian
12 in a container, ext4):
- recovery/061_hash_torn_primary_page: 9 subtests passed
- recovery/062_hash_vacuum_insert_crc: 4 subtests passed, none skipped
Passing the segment files from pg_walfile_name() works as expected,
and I did not see the "invalid WAL segment size" error again. No CRC
problem was reported either.
I only ran these two tests, once, on Linux ext4. I did not run
check-world or other platforms.
Thanks again for the work on this.
Best regards,
Joao Rito
Em sex., 13 de nov. de 2026 às 07:42, vignesh C <vignesh21@gmail.com> escreveu:
>
> On Thu, 12 Nov 2026 at 21:43, Joao Rito <joaovictor.rito@gmail.com> wrote:
> >
> > Hi Greg,
> >
> > Thank you for the v7 patch and the new recovery test.
> >
> > I tested v7 on a local build. While running 061_hash_vacuum_insert_crc on
> > Linux (ext4, meson build), subtest 2 failed for me with:y
> >
> > pg_waldump: error: invalid WAL segment size in WAL file
> > "000000010000000000000002" (0 bytes)
> >
> > Both LSNs are in segment ...0001, and segment ...0002 is a zero-filled
> > 16 MB file. When --path is a directory, pg_waldump seems to read the
> > segment size from the first WAL file readdir() returns, so the result
> > depends on directory order (here 0002 came first).
> >
> > Passing the segment file for $start_lsn (for example from pg_walfile_name)
> > worked for me by hand. Subtest 3 passed and I saw no CRC problem. I did
> > not apply the change to the test and rerun it under meson.
>
> Thanks for the comment, this is addressed in the v8 version patch attached.
> Apart from that, the following changes were done:
> 1) prepared back branch patches for the 0001 patch.
> 2) The test 068 was renamed to the next available 061 test file.
> 3) Most of the test code was common in
> hash_torn_primary_page_delete_first and
> hash_torn_primary_page_standby, merged them to a single test
> 4) the test added along with 0001 was not passing with the first patch
> alone, fixed it so that the first patch can be committed separately.
>
> Regards,
> Vignesh
^ permalink raw reply [nested|flat] 34+ messages in thread
* RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-13 10:21 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-13 19:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
1 sibling, 2 replies; 34+ messages in thread
From: Hayato Kuroda (Fujitsu) @ 2026-11-13 10:21 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; vignesh C <vignesh21@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>
Hi,
Thanks for updating the patch. Few more comments. Note that I did not review 0003,
because I was not sure it's intended to be pushed.
01.
```
+ * If buf is an overflow page, the primary bucket page is not
+ * changed and we hold only a pin on it, so it is not
+ * registered. Append its block number instead, and replay
+ * takes a cleanup lock on it. It is not needed otherwise
```
I think we should clarify why the primary bucket itself or block number should be
registered. Idea:
```
/*
* Replay must take a cleanup lock on the primary bucket page to
* serialize with scans on a hot standby. If buf is an overflow
* page, the unchanged primary page is held only by a pin, so append
* its block number instead of registering it. Otherwise block 0
* identifies the primary page.
*/
```
02.
```
+/*
+ * Take a cleanup lock on the primary bucket page of the bucket that a
+ * squeeze or delete record operates on, when that page is not one of the
+ * pages the record changes and so is not registered in it. Its block number
+ * is stored in the main data of the record, right after the fixed-size struct
+ * of rec_size bytes.
+ *
+ * This serializes replay against scans on a hot standby, which pin the
+ * primary bucket page for their whole duration; see the comments in the
+ * callers. The page is not modified, so nothing is done with it besides
+ * locking it. block_id must be a block of the same index registered in
+ * the record.
+ */
+static Buffer
+hash_xlog_lock_primary_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
```
In contrast this might be too detail, the user of the function might not need
such an info. How about:
```
/*
* Take a cleanup lock on an unregistered primary bucket page, whose
* block number is stored in the record's main data. This serializes
* replay against scans on a hot standby. block_id must identify a
* registered block of the same index.
*/
```
03.
```
+ * Register only the pages this record changes. The primary bucket
+ * page is registered only if it is the write page and is modified;
+ * otherwise we may hold only a pin on it, so append its block number
+ * and replay takes a cleanup lock on it.
```
Same as 01, we can clarify the reason why the primary bucket is needed. Idea:
```
/*
* Replay needs the primary bucket block number to acquire a cleanup
* lock. Register it as block 0 when it is modified; otherwise append
* its block number to the record.
*/
```
Best regards,
Hayato Kuroda
FUJITSU LIMITED
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
@ 2026-11-13 19:11 ` Greg Burd <greg@burd.me>
1 sibling, 0 replies; 34+ messages in thread
From: Greg Burd @ 2026-11-13 19:11 UTC (permalink / raw)
To: Hayato Kuroda <kuroda.hayato@fujitsu.com>; +Cc: vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; Joao Rito <joaovictor.rito@gmail.com>; pgsql-hackers@lists.postgresql.org
Hayato,
Thanks, these three are good and I have taken all of them verbatim in v10.
01. hashbucketcleanup: reworded to lead with why replay needs the
cleanup lock, then the overflow-page case.
/*
* Replay must take a cleanup lock on the primary bucket page to
* serialize with scans on a hot standby. If buf is an overflow
* page, the unchanged primary page is held only by a pin, so append
* its block number instead of registering it. Otherwise block 0
* identifies the primary page.
*/
02. hash_xlog_lock_primary_bucket doc: shortened to your version. The
detail it dropped (the block number sits right after the fixed-size
struct) is still carried by the Assert and the memcpy in the body,
so nothing is lost for a reader of the function.
/*
* Take a cleanup lock on an unregistered primary bucket page, whose
* block number is stored in the record's main data. This serializes
* replay against scans on a hot standby. block_id must identify a
* registered block of the same index.
*/
03. _hash_freeovflpage: same treatment as 01.
/*
* Replay needs the primary bucket block number to acquire a cleanup
* lock. Register it as block 0 when it is modified; otherwise append
* its block number to the record.
*/
On 0003: it is meant to be pushed. It is the recovery test that pins
down the CRC window 0002 closes, via the injection point in
XLogRecordAssemble that fires after the record CRC is computed and
before the record is copied. Without 0002 the test fails with
"incorrect resource manager data checksum"; with it the same
interleaving replays cleanly. I have kept it after 0002 so each commit
is self-contained, but it is fine to squash it into 0002 on commit if
you would rather the fix and its test land together.
This v10 is the same four-commit master series we converged on with
vignesh, rebased on 77bba5454f9, with the three comment changes above
and nothing else. hash.c, hash_xlog.c, hashovfl.c, the README and the
two headers are identical to vignesh's v8 apart from those comments.
One loose end for the group: vignesh's v8 merged the two torn-page
tests into one 061_hash_torn_primary_page.pl and moved the CRC test to
062. This v10 still carries my earlier split (068a/068b plus the CRC
test), because that is what I had validated. I am happy either way.
0001 (the torn-page redo fix) stands alone and is back-patchable;
0002-0004 are master only.
best.
-greg
Attachments: download all (4 files, .tar.gz)
v10-0001-Fix-hash-index-redo-reading-a-torn-primary-bucke.patch (text/x-patch, 19.5K) download
From 0f68e86cba7ac0ff4dec1b8ce11d37a1c60b0786 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 12 Nov 2026 16:12:44 +0000
Subject: [PATCH v10 v10 1/4] Fix hash index redo reading a torn primary bucket
page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 47 +++--
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
src/test/recovery/meson.build | 2 +
...68a_hash_torn_primary_page_delete_first.pl | 142 +++++++++++++++
.../t/068b_hash_torn_primary_page_standby.pl | 171 ++++++++++++++++++
6 files changed, 349 insertions(+), 17 deletions(-)
create mode 100644 src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl
create mode 100644 src/test/recovery/t/068b_hash_torn_primary_page_standby.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..0aaad828bf5 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -469,6 +470,34 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on the primary bucket page of a delete, squeeze or
+ * move-page-contents record during replay, when that page is registered
+ * (pin-only) as block 0 but not changed by the record. Returns the pinned
+ * and cleanup-locked buffer, which the caller must release at the end of the
+ * replay operation, or InvalidBuffer when the page is not read (see below).
+ *
+ * The lock serializes replay against scans on a hot standby, which pin the
+ * page for their whole duration. Scans can run only once hot standby accepts
+ * queries, so until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page image comes
+ * later in the WAL: that hazard exists only before consistency is reached, and
+ * queries are accepted only after that, so once HotStandbyActiveInReplay() is
+ * true any earlier image has already been replayed. We do not use the page
+ * contents here in any case.
+ */
+static Buffer
+hash_xlog_cleanup_lock_primary(XLogReaderState *record)
+{
+ Buffer bucketbuf = InvalidBuffer;
+
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true,
+ &bucketbuf);
+
+ return bucketbuf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -493,11 +522,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_cleanup_lock_primary(record);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -620,11 +645,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_cleanup_lock_primary(record);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -851,11 +872,7 @@ hash_xlog_delete(XLogReaderState *record)
action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_cleanup_lock_primary(record);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..e091a3e178b 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -390,7 +390,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4589,7 +4588,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 8786b6d3a8e..11d3eadef3e 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -216,6 +216,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..e7ff07ca880 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,8 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/068a_hash_torn_primary_page_delete_first.pl',
+ 't/068b_hash_torn_primary_page_standby.pl',
],
},
}
diff --git a/src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl b/src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl
new file mode 100644
index 00000000000..e61a0b98885
--- /dev/null
+++ b/src/test/recovery/t/068a_hash_torn_primary_page_delete_first.pl
@@ -0,0 +1,142 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test crash recovery when the primary bucket page of a hash bucket is torn,
+# and the full-page image that repairs it comes after the record that reads it.
+#
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$node->start;
+
+is($node->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $redo = $node->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# The entries of ids 451-600 are on the overflow page, those of ids 1-50 on the
+# primary page. The DELETE for the overflow page comes first; the VACUUM of
+# the primary page then changes it for the first time since the checkpoint, so
+# its record carries the full-page image of the page.
+$node->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$node->safe_psql('postgres', 'VACUUM t');
+$node->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$node->safe_psql('postgres', 'VACUUM t');
+
+my $relpath = $node->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $node->safe_psql('postgres', 'SHOW block_size');
+$node->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# Read the Hash records after the checkpoint.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--rmgr' => 'Hash',
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary bucket page's block number is not a registered block of the
+# overflow-page DELETE (the record carries it only as appended main data), so
+# find it from a record that does register it: a DELETE or SQUEEZE_PAGE marked
+# is_primary T references the primary bucket page as its first block.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #0: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout;
+
+# The overflow-page DELETE (is_primary F) reads the primary bucket page
+# pin-only to take the cleanup lock; it must come before the primary page's
+# first full-page image.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete,
+ 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout;
+
+# Where the first full-page image of the primary page is.
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+$node->stop('immediate');
+
+# Simulate a torn write of the primary page: keep the first half of its block
+# and overwrite the second half.
+if (defined $pblk)
+{
+ my $path = $node->data_dir . '/' . $relpath;
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $started = $node->start(fail_ok => 1);
+ok($started, 'crash recovery succeeds');
+if ($started)
+{
+ is( $node->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'the hash index gives the right result after recovery');
+ $node->stop;
+}
+else
+{
+ my $log = slurp_file($node->logfile);
+ diag("the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
diff --git a/src/test/recovery/t/068b_hash_torn_primary_page_standby.pl b/src/test/recovery/t/068b_hash_torn_primary_page_standby.pl
new file mode 100644
index 00000000000..d9a548a931e
--- /dev/null
+++ b/src/test/recovery/t/068b_hash_torn_primary_page_standby.pl
@@ -0,0 +1,171 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test a standby that starts from a base backup whose copy of the primary
+# bucket page of a hash bucket is torn, and the full-page image that repairs it
+# comes after the record that reads it.
+#
+
+use strict;
+use warnings FATAL => 'all';
+
+use File::Path qw(rmtree);
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1);
+$primary->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$primary->start;
+
+is($primary->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+my $relpath = $primary->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
+
+# Start a low-level backup, which does a checkpoint, and copy the files.
+my $backup_name = 'torn';
+my $backup_dir = $primary->backup_dir . '/' . $backup_name;
+my $psql = $primary->background_psql('postgres');
+$psql->query_safe("SET client_min_messages TO WARNING");
+$psql->set_query_timer_restart;
+$psql->query_safe("select pg_backup_start('torn primary page', true)");
+my $redo = $primary->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
+unlink("$backup_dir/postmaster.pid")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
+unlink("$backup_dir/postmaster.opts")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
+rmtree("$backup_dir/pg_wal")
+ or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
+mkdir("$backup_dir/pg_wal");
+
+# While the backup is in progress: the entries of ids 451-600 are on the
+# overflow page, those of ids 1-50 on the primary page. The DELETE for the
+# overflow page comes first; the VACUUM of the primary page then changes it for
+# the first time since the checkpoint of the backup, so its record carries the
+# full-page image of the page.
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# Read the Hash records after the redo pointer of the backup.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $primary->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--rmgr' => 'Hash',
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
+# block 1, the page that is changed.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #[01]: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout;
+
+# The first DELETE for an overflow page.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete,
+ 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout;
+
+# Where the first full-page image of the primary page is, relative to the
+# DELETE for the overflow page.
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+# The copy of the primary page in the backup is torn: keep the first half of
+# its block and overwrite the second half.
+if (defined $pblk)
+{
+ my $path = "$backup_dir/$relpath";
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+# End the backup, and save backup_label into the backup.
+my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
+$psql->quit;
+open(my $fh, '>', "$backup_dir/backup_label")
+ or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
+print $fh $backup_label;
+close($fh);
+
+# Start a hot standby from the backup. Replay starts at the redo pointer of
+# the backup, replays the DELETE for the overflow page first, and reaches the
+# consistency point only after the end of the backup, after the full-page
+# image of the primary page.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
+$standby->append_conf('postgresql.conf', 'hot_standby = on');
+
+my $started = $standby->start(fail_ok => 1);
+ok($started, 'the standby starts');
+if ($started)
+{
+ $primary->wait_for_catchup($standby);
+ is( $standby->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'the hash index gives the right result on the standby');
+}
+else
+{
+ my $log = slurp_file($standby->logfile);
+ diag("the standby did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.54.0
v10-0004-Remove-REGBUF_NO_CHANGE.patch (text/x-patch, 5.2K) download
From b438eb200e5e1a8e7797e3c600421d0a0ee54469 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:17:46 -0400
Subject: [PATCH v10 v10 4/4] Remove REGBUF_NO_CHANGE
With the previous commits, the hash index AM no longer registers any
pin-only or otherwise-unchanged buffer, so REGBUF_NO_CHANGE has no users
left. Remove the flag and restore the invariant that every registered
buffer is content-locked and dirty: XLogRegisterBuffer() asserts it
unconditionally again.
This also reverts the defensive measures added in 27caf4ca5ae5, which
let a REGBUF_NO_CHANGE buffer skip the full-page image forced by
wal_consistency_checking: XLogRecordAssemble() no longer special-cases
the flag, and verifyBackupPageConsistency() again asserts that a
registered block carries an image. 27caf4ca5ae5 remains in the back
branches, where this hash rework is not applied.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/transam/README | 5 ----
src/backend/access/transam/xloginsert.c | 28 ++++++-----------------
src/backend/access/transam/xlogrecovery.c | 7 +-----
src/include/access/xloginsert.h | 3 ---
4 files changed, 8 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/transam/README b/src/backend/access/transam/README
index 595afa01fa7..231106270fd 100644
--- a/src/backend/access/transam/README
+++ b/src/backend/access/transam/README
@@ -586,11 +586,6 @@ void XLogRegisterBuffer(uint8 block_id, Buffer buf, uint8 flags);
XLogRegisterBufData() is included in the WAL record even if a full-page
image is taken.
- The REGBUF_NO_CHANGE flag indicates that the buffer is registered without
- being modified by this record, and possibly without an exclusive content
- lock. wal_consistency_checking does not force a full-page image for such
- a buffer.
-
void XLogRegisterData(const void *data, int len);
XLogRegisterData is used to include arbitrary data in the WAL record. If
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index cd3359434e1..2d031e38594 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -257,22 +257,13 @@ XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Assert(begininsert_called);
/*
- * Ordinarily, the buffer should be exclusive-locked (or share-exclusive
- * in case of hint bits) and marked dirty before we get here, otherwise we
- * could end up violating one of the rules in access/transam/README.
- *
- * Some callers intentionally register a clean page and never update that
- * page's LSN; in that case they can pass the flag REGBUF_NO_CHANGE to
- * bypass these checks.
+ * The buffer should be exclusive-locked (or share-exclusive in case of
+ * hint bits) and marked dirty before we get here, otherwise we could end
+ * up violating one of the rules in access/transam/README.
*/
-#ifdef USE_ASSERT_CHECKING
- if (!(flags & REGBUF_NO_CHANGE))
- {
- Assert(BufferIsDirty(buffer));
- Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
- BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
- }
-#endif
+ Assert(BufferIsDirty(buffer));
+ Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
+ BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
if (block_id >= max_registered_block_id)
{
@@ -722,13 +713,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
- *
- * Do not force an image for a REGBUF_NO_CHANGE buffer.
*/
- if (regbuf->flags & REGBUF_NO_CHANGE)
- include_image = needs_backup;
- else
- include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
+ include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index e091a3e178b..1b2c9cc78e9 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2487,12 +2487,7 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- /*
- * Blocks registered with REGBUF_NO_CHANGE may have no image, see
- * XLogRecordAssemble(). Nothing to compare for these.
- */
- if (!XLogRecHasBlockImage(record, block_id))
- continue;
+ Assert(XLogRecHasBlockImage(record, block_id));
if (XLogRecBlockImageApply(record, block_id))
{
diff --git a/src/include/access/xloginsert.h b/src/include/access/xloginsert.h
index 86264564ebb..ddb1a85db59 100644
--- a/src/include/access/xloginsert.h
+++ b/src/include/access/xloginsert.h
@@ -38,9 +38,6 @@
* will be skipped) */
#define REGBUF_KEEP_DATA 0x10 /* include data even if a full-page image
* is taken */
-#define REGBUF_NO_CHANGE 0x20 /* intentionally register clean buffer; no
- * image is forced for WAL consistency
- * checking */
/* prototypes for public functions in xloginsert.c: */
extern void XLogBeginInsert(void);
--
2.54.0
v10-0003-Add-a-recovery-test-for-the-hash-WAL-pin-only-bu.patch (text/x-patch, 12.3K) download
From 1f5854520261d8afe37508818059e3186aa9bab9 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v10 v10 3/4] Add a recovery test for the hash WAL pin-only
bucket page fix
Add recovery/t/061_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
pg_waldump is pointed at the specific segment file holding the checked
range rather than the pg_wal directory: given a directory it takes the
segment size from the first file readdir() returns, which can be a
zero-filled future segment and then fails with "invalid WAL segment
size".
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Reported-by: Joao Rito <joaovictor.rito@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 +++
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_vacuum_insert_crc.pl | 187 ++++++++++++++++++
3 files changed, 210 insertions(+)
create mode 100644 src/test/recovery/t/061_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index e7ff07ca880..43bf2ef3aa4 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_vacuum_insert_crc.pl',
't/068a_hash_torn_primary_page_delete_first.pl',
't/068b_hash_torn_primary_page_standby.pl',
],
diff --git a/src/test/recovery/t/061_hash_vacuum_insert_crc.pl b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..ccc28646362
--- /dev/null
+++ b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
@@ -0,0 +1,187 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+my $start_walfile =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$start_lsn')");
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter. Point it at the
+# specific segment file holding the range, not at the pg_wal directory: given a
+# directory, pg_waldump takes the segment size from the first file readdir()
+# returns, which may be a zero-filled future segment, and then fails with
+# "invalid WAL segment size".
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $node->data_dir . '/pg_wal/' . $start_walfile,
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.54.0
v10-0002-Don-t-register-pin-only-primary-bucket-pages-in-.patch (text/x-patch, 23.2K) download
From 564ee69dde8dc9fd28b993ffda390b0ef7d9da1e Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v10 v10 2/4] Don't register pin-only primary bucket pages in
hash WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that no scan on a hot standby is in progress in the bucket, and
none can start, while tuples are removed or moved. That lock was
obtained by registering the page (pin-only) with REGBUF_NO_CHANGE; redo
never reads data from the block, the registration existed only for the
lock. That broke the rule that a registered buffer is one the caller
holds exclusively locked and dirty, and under wal_consistency_checking
it forced a full-page image of a page a concurrent inserter could still
modify, so the record CRC was computed over shifting data.
Stop registering the primary bucket page when the record does not change
it. When the page is not one of the pages the record changes, the
operation holds only a pin on it, so the record carries the page's block
number in its main data and replay reads that block and takes a cleanup
lock on it directly, at the same point and in the same order as before.
The block number is appended only in that case, so the records are no
larger than before in the common case where the primary bucket page is
registered.
After this change hash registers only buffers it holds exclusively
locked and dirty, and there are no REGBUF_NO_CHANGE users left.
The three record formats change, so bump XLOG_PAGE_MAGIC; master only.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/auNs8b_vS2OPdTL8@floki
---
src/backend/access/hash/README | 9 +++
src/backend/access/hash/hash.c | 18 ++---
src/backend/access/hash/hash_xlog.c | 110 +++++++++++++++++-----------
src/backend/access/hash/hashovfl.c | 99 +++++++++++--------------
src/include/access/hash_xlog.h | 37 +++++++---
src/include/access/xlog_internal.h | 2 +-
6 files changed, 152 insertions(+), 123 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record then carries its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..9a919654ce5 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -909,19 +909,17 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * Replay must take a cleanup lock on the primary bucket page
+ * to serialize with scans on a hot standby. If buf is an
+ * overflow page, the unchanged primary page is held only by a
+ * pin, so append its block number instead of registering it.
+ * Otherwise block 0 identifies the primary page.
*/
if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
- XLogRegisterBufData(1, deletable,
+ XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_DELETE);
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 0aaad828bf5..f7a30c8ea90 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -471,31 +471,42 @@ hash_xlog_split_complete(XLogReaderState *record)
}
/*
- * Take a cleanup lock on the primary bucket page of a delete, squeeze or
- * move-page-contents record during replay, when that page is registered
- * (pin-only) as block 0 but not changed by the record. Returns the pinned
- * and cleanup-locked buffer, which the caller must release at the end of the
- * replay operation, or InvalidBuffer when the page is not read (see below).
- *
- * The lock serializes replay against scans on a hot standby, which pin the
- * page for their whole duration. Scans can run only once hot standby accepts
- * queries, so until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page image comes
- * later in the WAL: that hazard exists only before consistency is reached, and
- * queries are accepted only after that, so once HotStandbyActiveInReplay() is
- * true any earlier image has already been replayed. We do not use the page
- * contents here in any case.
+ * Take a cleanup lock on an unregistered primary bucket page, whose block
+ * number is stored in the record's main data. This serializes replay against
+ * scans on a hot standby. block_id must identify a registered block of the
+ * same index.
*/
static Buffer
-hash_xlog_cleanup_lock_primary(XLogReaderState *record)
+hash_xlog_lock_primary_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
{
- Buffer bucketbuf = InvalidBuffer;
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ BlockNumber bucket_blkno;
+ Buffer buf;
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true,
- &bucketbuf);
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
- return bucketbuf;
+ /*
+ * The cleanup lock on the primary bucket page serializes replay against
+ * scans on a hot standby, which pin the page for their whole duration.
+ * Scans can run only once hot standby accepts queries, so until then we
+ * need not read or lock the page. Skipping the read also sidesteps a torn
+ * copy of the page whose repairing full-page image comes later in the WAL:
+ * that hazard exists only before consistency is reached, and queries are
+ * accepted only after that, so once HotStandbyActiveInReplay() is true any
+ * earlier image has already been replayed. Redo never uses the page's
+ * contents here in any case.
+ */
+ if (!HotStandbyActiveInReplay())
+ return InvalidBuffer;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
}
/*
@@ -519,12 +530,12 @@ hash_xlog_move_page_contents(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
- bucketbuf = hash_xlog_cleanup_lock_primary(record);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashMovePageContents);
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
}
/* replay the record for adding entries in overflow buffer */
@@ -536,7 +547,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
Size datalen;
uint16 ninserted = 0;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -575,13 +586,13 @@ hash_xlog_move_page_contents(XLogReaderState *record)
}
/* replay the record for deleting entries from overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &deletebuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &deletebuf) == BLK_NEEDS_REDO)
{
Page page;
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 2, &len);
+ ptr = XLogRecGetBlockData(record, 1, &len);
page = BufferGetPage(deletebuf);
@@ -642,13 +653,26 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ {
+ /*
+ * If the primary bucket page is modified, it is registered as block
+ * 0 and read for redo. Otherwise, acquire its cleanup lock
+ * separately.
+ */
+ if (XLogRecHasBlockRef(record, 0))
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
+ action = BLK_NOTFOUND;
+ }
+ }
else
{
- bucketbuf = hash_xlog_cleanup_lock_primary(record);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
else
action = BLK_NOTFOUND;
}
@@ -663,7 +687,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint16 ninserted = 0;
bool mod_wbuf = false;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -729,7 +753,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
}
/* replay the record for initializing overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &ovflbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &ovflbuf) == BLK_NEEDS_REDO)
{
Page ovflpage;
HashPageOpaque ovflopaque;
@@ -754,7 +778,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/* replay the record for page previous to the freed overflow page */
if (!xldata->is_prev_bucket_same_wrt &&
- XLogReadBufferForRedo(record, 3, &prevbuf) == BLK_NEEDS_REDO)
+ XLogReadBufferForRedo(record, 2, &prevbuf) == BLK_NEEDS_REDO)
{
Page prevpage = BufferGetPage(prevbuf);
HashPageOpaque prevopaque = HashPageGetOpaque(prevpage);
@@ -768,11 +792,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(prevbuf);
/* replay the record for page next to the freed overflow page */
- if (XLogRecHasBlockRef(record, 4))
+ if (XLogRecHasBlockRef(record, 3))
{
Buffer nextbuf;
- if (XLogReadBufferForRedo(record, 4, &nextbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 3, &nextbuf) == BLK_NEEDS_REDO)
{
Page nextpage = BufferGetPage(nextbuf);
HashPageOpaque nextopaque = HashPageGetOpaque(nextpage);
@@ -799,7 +823,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* index updates can be happening concurrently.
*/
/* replay the record for bitmap page */
- if (XLogReadBufferForRedo(record, 5, &mapbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 4, &mapbuf) == BLK_NEEDS_REDO)
{
Page mappage = BufferGetPage(mapbuf);
uint32 *freep = NULL;
@@ -809,7 +833,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
freep = HashPageGetBitmap(mappage);
- data = XLogRecGetBlockData(record, 5, &datalen);
+ data = XLogRecGetBlockData(record, 4, &datalen);
bitmap_page_bit = (uint32 *) data;
CLRBIT(freep, *bitmap_page_bit);
@@ -821,11 +845,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(mapbuf);
/* replay the record for meta page */
- if (XLogRecHasBlockRef(record, 6))
+ if (XLogRecHasBlockRef(record, 5))
{
Buffer metabuf;
- if (XLogReadBufferForRedo(record, 6, &metabuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 5, &metabuf) == BLK_NEEDS_REDO)
{
HashMetaPage metap;
Page page;
@@ -833,7 +857,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint32 *firstfree_ovflpage;
Size datalen;
- data = XLogRecGetBlockData(record, 6, &datalen);
+ data = XLogRecGetBlockData(record, 5, &datalen);
firstfree_ovflpage = (uint32 *) data;
page = BufferGetPage(metabuf);
@@ -869,12 +893,12 @@ hash_xlog_delete(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_primary_bucket_page)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &deletebuf);
else
{
- bucketbuf = hash_xlog_cleanup_lock_primary(record);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashDelete);
- action = XLogReadBufferForRedo(record, 1, &deletebuf);
+ action = XLogReadBufferForRedo(record, 0, &deletebuf);
}
/* replay the record for deleting entries in bucket page */
@@ -883,7 +907,7 @@ hash_xlog_delete(XLogReaderState *record)
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 1, &len);
+ ptr = XLogRecGetBlockData(record, 0, &len);
page = BufferGetPage(deletebuf);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..35f214767bd 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,6 +660,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
@@ -667,45 +672,26 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Replay needs the primary bucket block number to acquire a cleanup
+ * lock. Register it as block 0 when it is modified; otherwise append
+ * its block number to the record.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- if (nitups > 0)
- {
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
+ if (mod_wbuf)
{
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(0, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
+ }
}
- XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(1, ovflbuf, REGBUF_STANDARD);
/*
* If prevpage and the writepage (block in which we are moving tuples
@@ -714,18 +700,18 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* writepage.
*/
if (BufferIsValid(prevbuf) && !is_prev_bucket_same_wrt)
- XLogRegisterBuffer(3, prevbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(2, prevbuf, REGBUF_STANDARD);
if (BufferIsValid(nextbuf))
- XLogRegisterBuffer(4, nextbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(3, nextbuf, REGBUF_STANDARD);
- XLogRegisterBuffer(5, mapbuf, REGBUF_STANDARD);
- XLogRegisterBufData(5, &bitmapbit, sizeof(uint32));
+ XLogRegisterBuffer(4, mapbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(4, &bitmapbit, sizeof(uint32));
if (update_metap)
{
- XLogRegisterBuffer(6, metabuf, REGBUF_STANDARD);
- XLogRegisterBufData(6, &metap->hashm_firstfree, sizeof(uint32));
+ XLogRegisterBuffer(5, metabuf, REGBUF_STANDARD);
+ XLogRegisterBufData(5, &metap->hashm_firstfree, sizeof(uint32));
}
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SQUEEZE_PAGE);
@@ -966,10 +952,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -998,25 +986,22 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, itup_offsets,
nitups * sizeof(OffsetNumber));
for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
- XLogRegisterBuffer(2, rbuf, REGBUF_STANDARD);
- XLogRegisterBufData(2, deletable,
+ XLogRegisterBuffer(1, rbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_MOVE_PAGE_CONTENTS);
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..0bb0d0590f5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,9 +129,13 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing moved tuples
- * Backup Blk 2: page from which tuples will be removed
+ * Backup Blk 0: page containing moved tuples
+ * Backup Blk 1: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
@@ -149,13 +153,18 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
- * Backup Blk 2: freed overflow page
- * Backup Blk 3: page previous to the freed overflow page
- * Backup Blk 4: page next to the freed overflow page
- * Backup Blk 5: bitmap page containing info of freed overflow page
- * Backup Blk 6: meta page
+ * Backup Blk 0: page containing tuples moved from freed overflow page, if
+ * it is modified
+ * Backup Blk 1: freed overflow page
+ * Backup Blk 2: page previous to the freed overflow page
+ * Backup Blk 3: page next to the freed overflow page
+ * Backup Blk 4: bitmap page containing info of freed overflow page
+ * Backup Blk 5: meta page
+ *
+ * The primary bucket page is registered only as block 0, when it is the
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
@@ -179,8 +188,12 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page from which tuples are deleted
+ * Backup Blk 0: page from which tuples are deleted
+ *
+ * If block 0 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
--
2.54.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
@ 2026-11-14 15:02 ` Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
1 sibling, 1 reply; 34+ messages in thread
From: Greg Burd @ 2026-11-14 15:02 UTC (permalink / raw)
To: Hayato Kuroda <kuroda.hayato@fujitsu.com>; +Cc: vignesh C <vignesh21@gmail.com>; Joao Rito <joaovictor.rito@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
Hayato, vignesh, Joao,
v11 attached. This is vignesh's v8 as the base, with Hayato's three
comment changes applied and nothing else changed in the code. I built
it and ran it so we have one version that is current, reviewed, and
tested end to end.
What changed since my v10:
- Adopted vignesh's v8 layout as canonical: the merged
061_hash_torn_primary_page.pl, the CRC test as
062_hash_vacuum_insert_crc.pl, the standalone-0001 fix, and the
REL15..REL19 back-branch patches for 0001. My earlier 068a/068b
split is gone.
- Applied Hayato's three comment changes to 0002, verbatim:
hashbucketcleanup and _hash_freeovflpage now lead with why replay
needs the cleanup lock, and the hash_xlog_lock_primary_bucket doc is
the shorter version.
Testing, rebased on current master (70c4a57b64d):
- Full recovery suite, autoconf UBSan build
(-O2 -fsanitize=alignment,undefined -fno-sanitize-recover=all) with
TEMP_CONFIG=src/tools/ci/pg_ci_base.conf and
PG_TEST_EXTRA=wal_consistency_checking, run in parallel: 61 files,
838 tests, all pass. 061 and 062 both pass.
- 0001 alone: 061_hash_torn_primary_page passes 9/9, so the fix and
its test are committable separately, as vignesh intended.
- The REL15..REL19 0001 patches apply to their branches. I built
REL19 under the same UBSan flags and its 061 passes 9/9. The
back-branch 0001 is unchanged from vignesh's v8; Hayato's comments
are all in 0002, which is master only.
Thanks Joao for retesting v8 on ext4 and confirming the pg_waldump
segment-size fix holds.
On 0003: it is meant to be pushed. It is the recovery test that pins
down the CRC window 0002 closes, through the injection point in
XLogRecordAssemble that fires after the record CRC is computed and
before the record is copied. Without 0002 it fails with "incorrect
resource manager data checksum"; with it the same interleaving replays
cleanly. I kept it as its own commit, but it is fine to squash it into
0002 on commit if you would rather the fix and its test land together.
0001 (the torn-page redo fix) stands alone and is back-patchable;
0002-0004 are master only.
Greg
Attachments: download all (5 files, .tar.gz)
v11-0004-Remove-REGBUF_NO_CHANGE.patch (text/x-patch, 5.2K) download
From 8f2dc1a9bf0bdd60fdc8118bbe0b77224078dc03 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:17:46 -0400
Subject: [PATCH v11 4/4] Remove REGBUF_NO_CHANGE
With the previous commits, the hash index AM no longer registers any
pin-only or otherwise-unchanged buffer, so REGBUF_NO_CHANGE has no users
left. Remove the flag and restore the invariant that every registered
buffer is content-locked and dirty: XLogRegisterBuffer() asserts it
unconditionally again.
This also reverts the defensive measures added in 27caf4ca5ae5, which
let a REGBUF_NO_CHANGE buffer skip the full-page image forced by
wal_consistency_checking: XLogRecordAssemble() no longer special-cases
the flag, and verifyBackupPageConsistency() again asserts that a
registered block carries an image. 27caf4ca5ae5 remains in the back
branches, where this hash rework is not applied.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/transam/README | 5 ----
src/backend/access/transam/xloginsert.c | 28 ++++++-----------------
src/backend/access/transam/xlogrecovery.c | 7 +-----
src/include/access/xloginsert.h | 3 ---
4 files changed, 8 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/transam/README b/src/backend/access/transam/README
index 595afa01fa7..231106270fd 100644
--- a/src/backend/access/transam/README
+++ b/src/backend/access/transam/README
@@ -586,11 +586,6 @@ void XLogRegisterBuffer(uint8 block_id, Buffer buf, uint8 flags);
XLogRegisterBufData() is included in the WAL record even if a full-page
image is taken.
- The REGBUF_NO_CHANGE flag indicates that the buffer is registered without
- being modified by this record, and possibly without an exclusive content
- lock. wal_consistency_checking does not force a full-page image for such
- a buffer.
-
void XLogRegisterData(const void *data, int len);
XLogRegisterData is used to include arbitrary data in the WAL record. If
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index cd3359434e1..2d031e38594 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -257,22 +257,13 @@ XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Assert(begininsert_called);
/*
- * Ordinarily, the buffer should be exclusive-locked (or share-exclusive
- * in case of hint bits) and marked dirty before we get here, otherwise we
- * could end up violating one of the rules in access/transam/README.
- *
- * Some callers intentionally register a clean page and never update that
- * page's LSN; in that case they can pass the flag REGBUF_NO_CHANGE to
- * bypass these checks.
+ * The buffer should be exclusive-locked (or share-exclusive in case of
+ * hint bits) and marked dirty before we get here, otherwise we could end
+ * up violating one of the rules in access/transam/README.
*/
-#ifdef USE_ASSERT_CHECKING
- if (!(flags & REGBUF_NO_CHANGE))
- {
- Assert(BufferIsDirty(buffer));
- Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
- BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
- }
-#endif
+ Assert(BufferIsDirty(buffer));
+ Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
+ BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
if (block_id >= max_registered_block_id)
{
@@ -722,13 +713,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
- *
- * Do not force an image for a REGBUF_NO_CHANGE buffer.
*/
- if (regbuf->flags & REGBUF_NO_CHANGE)
- include_image = needs_backup;
- else
- include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
+ include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index e091a3e178b..1b2c9cc78e9 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2487,12 +2487,7 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- /*
- * Blocks registered with REGBUF_NO_CHANGE may have no image, see
- * XLogRecordAssemble(). Nothing to compare for these.
- */
- if (!XLogRecHasBlockImage(record, block_id))
- continue;
+ Assert(XLogRecHasBlockImage(record, block_id));
if (XLogRecBlockImageApply(record, block_id))
{
diff --git a/src/include/access/xloginsert.h b/src/include/access/xloginsert.h
index 86264564ebb..ddb1a85db59 100644
--- a/src/include/access/xloginsert.h
+++ b/src/include/access/xloginsert.h
@@ -38,9 +38,6 @@
* will be skipped) */
#define REGBUF_KEEP_DATA 0x10 /* include data even if a full-page image
* is taken */
-#define REGBUF_NO_CHANGE 0x20 /* intentionally register clean buffer; no
- * image is forced for WAL consistency
- * checking */
/* prototypes for public functions in xloginsert.c: */
extern void XLogBeginInsert(void);
--
2.54.0
v11-0001-Fix-hash-index-redo-reading-a-torn-primary-bucke.patch (text/x-patch, 17.2K) download
From cf3df46e479213dce38798118463f9382147281a Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 12 Nov 2026 12:58:59 +0000
Subject: [PATCH v11 1/4] Fix hash index redo reading a torn primary bucket
page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 43 +++-
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_torn_primary_page.pl | 226 ++++++++++++++++++
5 files changed, 263 insertions(+), 11 deletions(-)
create mode 100644 src/test/recovery/t/061_hash_torn_primary_page.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..e1318bf97db 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -494,10 +495,18 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -621,10 +630,18 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -852,10 +869,18 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..e091a3e178b 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -390,7 +390,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4589,7 +4588,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 8786b6d3a8e..11d3eadef3e 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -216,6 +216,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..785f2d820b1 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_torn_primary_page.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
new file mode 100644
index 00000000000..3b71fb409ed
--- /dev/null
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -0,0 +1,226 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test redo of a hash VACUUM record that reads a torn primary bucket page, whose
+# repairing full-page image comes later in the WAL, in a standby started from a
+# base backup and in crash recovery. Data checksums must be on, so that the
+# torn page is detected.
+
+use strict;
+use warnings FATAL => 'all';
+
+use File::Path qw(rmtree);
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+# Tear a block of a relation file, as a torn write does: keep the first half of
+# the block and overwrite the second half with random bytes, so that its
+# checksum does not match.
+sub tear_page
+{
+ my ($path, $pblk, $bs) = @_;
+
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1);
+$primary->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$primary->start;
+
+is($primary->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary page holding about 407 entries and
+# an overflow page with the rest.
+$primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (id int, k int) WITH (autovacuum_enabled = false);
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT i, 1 FROM generate_series(1, 600) i;
+});
+my $relpath = $primary->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
+
+# Start a low-level backup, which does a checkpoint, and copy the files.
+my $backup_name = 'torn';
+my $backup_dir = $primary->backup_dir . '/' . $backup_name;
+my $psql = $primary->background_psql('postgres');
+$psql->query_safe("SET client_min_messages TO WARNING");
+$psql->set_query_timer_restart;
+$psql->query_safe("select pg_backup_start('torn primary page', true)");
+my $redo = $primary->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# Copy the data directory of the running server, as a backup does. Remove what
+# must not be in a backup, as pg_basebackup does: postmaster.pid, which would
+# make a server started from the copy think that the primary's postmaster is
+# still running, postmaster.opts, which only records how the primary was
+# started, and the WAL segments, which are copied at an arbitrary moment, and
+# which the standby gets by streaming, starting at the redo pointer of the
+# backup. The server expects pg_wal to exist, so create it empty.
+PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
+unlink("$backup_dir/postmaster.pid")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
+unlink("$backup_dir/postmaster.opts")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
+rmtree("$backup_dir/pg_wal")
+ or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
+mkdir("$backup_dir/pg_wal");
+
+# While the backup is in progress: the entries of ids 451-600 are on the
+# overflow page, those of ids 1-50 on the primary page. The DELETE for the
+# overflow page comes first; the VACUUM of the primary page then changes it for
+# the first time since the checkpoint of the backup, so its record carries the
+# full-page image of the page.
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id > 450');
+$primary->safe_psql('postgres', 'VACUUM t');
+$primary->safe_psql('postgres', 'DELETE FROM t WHERE id <= 50');
+$primary->safe_psql('postgres', 'VACUUM t');
+
+# Read the Hash records written since the checkpoint.
+my $end_lsn =
+ $primary->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# The first and the last WAL segment of the range.
+my $start_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$redo')");
+my $end_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Dump the Hash records from the redo pointer of the backup to the end of the
+# WAL written so far. The output is parsed below.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $primary->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
+# block 1, the page that is changed.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout, $stderr;
+
+# The DELETE for an overflow page has to come before the first full-page image
+# of the primary page.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete, 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout, $stderr;
+
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout, $stderr;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+# Tear the copy of the primary page in the backup.
+tear_page("$backup_dir/$relpath", $pblk, $bs) if defined $pblk;
+
+# End the backup, and save backup_label into the backup.
+my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
+$psql->quit;
+open(my $fh, '>', "$backup_dir/backup_label")
+ or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
+print $fh $backup_label;
+close($fh);
+
+###############################################################################
+# A standby started from the backup
+###############################################################################
+
+# Replay starts at the redo pointer of the backup, replays the DELETE for the
+# overflow page first, and reaches the consistency point only after the end of
+# the backup, after the full-page image of the primary page.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
+$standby->append_conf('postgresql.conf', 'hot_standby = on');
+
+my $started = $standby->start(fail_ok => 1);
+ok($started, 'standby: the standby starts');
+if ($started)
+{
+ $primary->wait_for_catchup($standby);
+ is( $standby->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'standby: the hash index gives the right result');
+ $standby->stop;
+}
+else
+{
+ my $log = slurp_file($standby->logfile);
+ diag("standby: the standby did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
+}
+
+###############################################################################
+# Crash recovery of the primary
+###############################################################################
+
+# There was no checkpoint since the one of the backup, so crash recovery
+# replays the same records from the same redo pointer. Tear the primary's own
+# copy of the page.
+$primary->stop('immediate');
+tear_page($primary->data_dir . '/' . $relpath, $pblk, $bs) if defined $pblk;
+
+$started = $primary->start(fail_ok => 1);
+ok($started, 'crash recovery: the server starts');
+if ($started)
+{
+ is( $primary->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ '400',
+ 'crash recovery: the hash index gives the right result');
+}
+else
+{
+ my $log = slurp_file($primary->logfile);
+ diag("crash recovery: the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.54.0
v11-0003-Add-a-recovery-test-for-the-hash-WAL-pin-only-bu.patch (text/x-patch, 12.0K) download
From 8cf7e1a606fafb4b43d8e92cbc2e73156af81826 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v11 3/4] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/062_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 ++
src/test/recovery/meson.build | 1 +
.../recovery/t/062_hash_vacuum_insert_crc.pl | 191 ++++++++++++++++++
3 files changed, 214 insertions(+)
create mode 100644 src/test/recovery/t/062_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index 785f2d820b1..be397ea20ed 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -70,6 +70,7 @@ tests += {
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
't/061_hash_torn_primary_page.pl',
+ 't/062_hash_vacuum_insert_crc.pl',
],
},
}
diff --git a/src/test/recovery/t/062_hash_vacuum_insert_crc.pl b/src/test/recovery/t/062_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..89f7611af12
--- /dev/null
+++ b/src/test/recovery/t/062_hash_vacuum_insert_crc.pl
@@ -0,0 +1,191 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# The first and the last WAL segment of the range. With only --path, pg_waldump
+# takes the WAL segment size from the first file readdir() returns, which can be
+# a zero-filled, unused segment, and then fails with "invalid WAL segment size".
+# Naming the segments makes it read the size from the first of them.
+my $start_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$start_lsn')");
+my $end_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.54.0
back-patches.tgz.nocfbot (application/octet-stream, 7.0K) download
v11-0002-Don-t-register-pin-only-primary-bucket-pages-in-.patch (text/x-patch, 25.2K) download
From 63d13c207f9c0ee14be39baecf81ffa8eabdd49e Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v11 2/4] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that no scan on a hot standby is in progress in the bucket, and
none can start, while tuples are removed or moved. That lock was
obtained by registering the page (pin-only) with REGBUF_NO_CHANGE; redo
never reads data from the block, the registration existed only for the
lock. That broke the rule that a registered buffer is one the caller
holds exclusively locked and dirty, and under wal_consistency_checking
it forced a full-page image of a page a concurrent inserter could still
modify, so the record CRC was computed over shifting data.
Stop registering the primary bucket page when the record does not change
it. When the page is not one of the pages the record changes, the
operation holds only a pin on it, so the record carries the page's block
number in its main data and replay reads that block and takes a cleanup
lock on it directly, at the same point and in the same order as before.
The block number is appended only in that case, so the records are no
larger than before in the common case where the primary bucket page is
registered.
After this change hash registers only buffers it holds exclusively
locked and dirty, and there are no REGBUF_NO_CHANGE users left.
The three record formats change, so bump XLOG_PAGE_MAGIC; master only.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/auNs8b_vS2OPdTL8@floki
---
src/backend/access/hash/README | 9 ++
src/backend/access/hash/hash.c | 18 ++-
src/backend/access/hash/hash_xlog.c | 132 ++++++++++--------
src/backend/access/hash/hashovfl.c | 99 ++++++-------
src/include/access/hash_xlog.h | 37 +++--
src/include/access/xlog_internal.h | 2 +-
.../recovery/t/061_hash_torn_primary_page.pl | 6 +-
7 files changed, 162 insertions(+), 141 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record then carries its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..9a919654ce5 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -909,19 +909,17 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * Replay must take a cleanup lock on the primary bucket page
+ * to serialize with scans on a hot standby. If buf is an
+ * overflow page, the unchanged primary page is held only by a
+ * pin, so append its block number instead of registering it.
+ * Otherwise block 0 identifies the primary page.
*/
if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
- XLogRegisterBufData(1, deletable,
+ XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_DELETE);
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e1318bf97db..f7a30c8ea90 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -470,6 +470,45 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on an unregistered primary bucket page, whose block
+ * number is stored in the record's main data. This serializes replay against
+ * scans on a hot standby. block_id must identify a registered block of the
+ * same index.
+ */
+static Buffer
+hash_xlog_lock_primary_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ BlockNumber bucket_blkno;
+ Buffer buf;
+
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
+ /*
+ * The cleanup lock on the primary bucket page serializes replay against
+ * scans on a hot standby, which pin the page for their whole duration.
+ * Scans can run only once hot standby accepts queries, so until then we
+ * need not read or lock the page. Skipping the read also sidesteps a torn
+ * copy of the page whose repairing full-page image comes later in the WAL:
+ * that hazard exists only before consistency is reached, and queries are
+ * accepted only after that, so once HotStandbyActiveInReplay() is true any
+ * earlier image has already been replayed. Redo never uses the page's
+ * contents here in any case.
+ */
+ if (!HotStandbyActiveInReplay())
+ return InvalidBuffer;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -491,24 +530,12 @@ hash_xlog_move_page_contents(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
- */
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashMovePageContents);
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
}
/* replay the record for adding entries in overflow buffer */
@@ -520,7 +547,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
Size datalen;
uint16 ninserted = 0;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -559,13 +586,13 @@ hash_xlog_move_page_contents(XLogReaderState *record)
}
/* replay the record for deleting entries from overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &deletebuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &deletebuf) == BLK_NEEDS_REDO)
{
Page page;
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 2, &len);
+ ptr = XLogRecGetBlockData(record, 1, &len);
page = BufferGetPage(deletebuf);
@@ -626,25 +653,26 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
- else
{
/*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
+ * If the primary bucket page is modified, it is registered as block
+ * 0 and read for redo. Otherwise, acquire its cleanup lock
+ * separately.
*/
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (XLogRecHasBlockRef(record, 0))
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
+ action = BLK_NOTFOUND;
+ }
+ }
+ else
+ {
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
else
action = BLK_NOTFOUND;
}
@@ -659,7 +687,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint16 ninserted = 0;
bool mod_wbuf = false;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -725,7 +753,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
}
/* replay the record for initializing overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &ovflbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &ovflbuf) == BLK_NEEDS_REDO)
{
Page ovflpage;
HashPageOpaque ovflopaque;
@@ -750,7 +778,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/* replay the record for page previous to the freed overflow page */
if (!xldata->is_prev_bucket_same_wrt &&
- XLogReadBufferForRedo(record, 3, &prevbuf) == BLK_NEEDS_REDO)
+ XLogReadBufferForRedo(record, 2, &prevbuf) == BLK_NEEDS_REDO)
{
Page prevpage = BufferGetPage(prevbuf);
HashPageOpaque prevopaque = HashPageGetOpaque(prevpage);
@@ -764,11 +792,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(prevbuf);
/* replay the record for page next to the freed overflow page */
- if (XLogRecHasBlockRef(record, 4))
+ if (XLogRecHasBlockRef(record, 3))
{
Buffer nextbuf;
- if (XLogReadBufferForRedo(record, 4, &nextbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 3, &nextbuf) == BLK_NEEDS_REDO)
{
Page nextpage = BufferGetPage(nextbuf);
HashPageOpaque nextopaque = HashPageGetOpaque(nextpage);
@@ -795,7 +823,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* index updates can be happening concurrently.
*/
/* replay the record for bitmap page */
- if (XLogReadBufferForRedo(record, 5, &mapbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 4, &mapbuf) == BLK_NEEDS_REDO)
{
Page mappage = BufferGetPage(mapbuf);
uint32 *freep = NULL;
@@ -805,7 +833,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
freep = HashPageGetBitmap(mappage);
- data = XLogRecGetBlockData(record, 5, &datalen);
+ data = XLogRecGetBlockData(record, 4, &datalen);
bitmap_page_bit = (uint32 *) data;
CLRBIT(freep, *bitmap_page_bit);
@@ -817,11 +845,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(mapbuf);
/* replay the record for meta page */
- if (XLogRecHasBlockRef(record, 6))
+ if (XLogRecHasBlockRef(record, 5))
{
Buffer metabuf;
- if (XLogReadBufferForRedo(record, 6, &metabuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 5, &metabuf) == BLK_NEEDS_REDO)
{
HashMetaPage metap;
Page page;
@@ -829,7 +857,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint32 *firstfree_ovflpage;
Size datalen;
- data = XLogRecGetBlockData(record, 6, &datalen);
+ data = XLogRecGetBlockData(record, 5, &datalen);
firstfree_ovflpage = (uint32 *) data;
page = BufferGetPage(metabuf);
@@ -865,24 +893,12 @@ hash_xlog_delete(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_primary_bucket_page)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
- */
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashDelete);
- action = XLogReadBufferForRedo(record, 1, &deletebuf);
+ action = XLogReadBufferForRedo(record, 0, &deletebuf);
}
/* replay the record for deleting entries in bucket page */
@@ -891,7 +907,7 @@ hash_xlog_delete(XLogReaderState *record)
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 1, &len);
+ ptr = XLogRecGetBlockData(record, 0, &len);
page = BufferGetPage(deletebuf);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..35f214767bd 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,6 +660,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
@@ -667,45 +672,26 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Replay needs the primary bucket block number to acquire a cleanup
+ * lock. Register it as block 0 when it is modified; otherwise append
+ * its block number to the record.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- if (nitups > 0)
- {
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
+ if (mod_wbuf)
{
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(0, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
+ }
}
- XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(1, ovflbuf, REGBUF_STANDARD);
/*
* If prevpage and the writepage (block in which we are moving tuples
@@ -714,18 +700,18 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* writepage.
*/
if (BufferIsValid(prevbuf) && !is_prev_bucket_same_wrt)
- XLogRegisterBuffer(3, prevbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(2, prevbuf, REGBUF_STANDARD);
if (BufferIsValid(nextbuf))
- XLogRegisterBuffer(4, nextbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(3, nextbuf, REGBUF_STANDARD);
- XLogRegisterBuffer(5, mapbuf, REGBUF_STANDARD);
- XLogRegisterBufData(5, &bitmapbit, sizeof(uint32));
+ XLogRegisterBuffer(4, mapbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(4, &bitmapbit, sizeof(uint32));
if (update_metap)
{
- XLogRegisterBuffer(6, metabuf, REGBUF_STANDARD);
- XLogRegisterBufData(6, &metap->hashm_firstfree, sizeof(uint32));
+ XLogRegisterBuffer(5, metabuf, REGBUF_STANDARD);
+ XLogRegisterBufData(5, &metap->hashm_firstfree, sizeof(uint32));
}
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SQUEEZE_PAGE);
@@ -966,10 +952,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -998,25 +986,22 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, itup_offsets,
nitups * sizeof(OffsetNumber));
for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
- XLogRegisterBuffer(2, rbuf, REGBUF_STANDARD);
- XLogRegisterBufData(2, deletable,
+ XLogRegisterBuffer(1, rbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_MOVE_PAGE_CONTENTS);
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..0bb0d0590f5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,9 +129,13 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing moved tuples
- * Backup Blk 2: page from which tuples will be removed
+ * Backup Blk 0: page containing moved tuples
+ * Backup Blk 1: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
@@ -149,13 +153,18 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
- * Backup Blk 2: freed overflow page
- * Backup Blk 3: page previous to the freed overflow page
- * Backup Blk 4: page next to the freed overflow page
- * Backup Blk 5: bitmap page containing info of freed overflow page
- * Backup Blk 6: meta page
+ * Backup Blk 0: page containing tuples moved from freed overflow page, if
+ * it is modified
+ * Backup Blk 1: freed overflow page
+ * Backup Blk 2: page previous to the freed overflow page
+ * Backup Blk 3: page next to the freed overflow page
+ * Backup Blk 4: bitmap page containing info of freed overflow page
+ * Backup Blk 5: meta page
+ *
+ * The primary bucket page is registered only as block 0, when it is the
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
@@ -179,8 +188,12 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page from which tuples are deleted
+ * Backup Blk 0: page from which tuples are deleted
+ *
+ * If block 0 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
index 3b71fb409ed..eaf3747f04c 100644
--- a/src/test/recovery/t/061_hash_torn_primary_page.pl
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -117,13 +117,13 @@ IPC::Run::run(
'2>' => \$stderr);
my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
-# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
-# block 1, the page that is changed.
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T changes it, so
+# it is the first block reference of the record.
my $pblk;
for my $r (@records)
{
if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
- && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ && $r =~ /blkref #0: rel \S+ blk (\d+)/)
{
$pblk = $1;
last;
--
2.54.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-14 20:35 ` Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 34+ messages in thread
From: Greg Burd @ 2026-11-14 20:35 UTC (permalink / raw)
To: Hayato Kuroda <kuroda.hayato@fujitsu.com>; vignesh C <vignesh21@gmail.com>; Joao Rito <joaovictor.rito@gmail.com>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
Hayato, vignesh, Joao,
v12 attached. Same series as v11, with one fix: the new torn-page test
failed CI on 32-bit, and this corrects it. Code is unchanged from v11.
The problem: 061_hash_torn_primary_page built its bucket with fixed row
counts and fixed id ranges (DELETE id > 450, then DELETE id <= 50)
tuned to the 64-bit page layout. On 32-bit an index tuple is smaller,
so more entries fit per page and the id ranges no longer map to the
same pages. The first VACUUM then removed dead entries from the primary
bucket page too, so that page got its own full-page image before the
overflow delete, and the test's premise (an overflow delete is replayed
before the primary page's image) no longer held. It failed on the
32-bit, MinGW and Windows VS jobs; 64-bit passed.
The fix makes the workload independent of how many entries fit on a
page. It deletes exactly the index entries that live on the overflow
pages, read from the index with pageinspect:
DELETE FROM t WHERE ctid IN (
SELECT i.ctid
FROM generate_series(1, pg_relation_size('t_i') / block_size - 1) b
CROSS JOIN LATERAL hash_page_items(get_raw_page('t_i', b)) i
WHERE hash_page_type(get_raw_page('t_i', b)) = 'overflow');
So VACUUM removes dead entries only from the overflow chain, never from
the primary bucket page, and the overflow delete is logged with the
primary page held pin-only. The squeeze that follows is the first record
to change the primary page since the backup checkpoint, so it carries
the image that repairs the torn page on replay. The table now uses a
single key column with heap fillfactor 100, and the empty table is
vacuumed before the index is built so hashbuild() starts with the
minimum two buckets; both keep the layout fixed across architectures.
The expected live-row count is read from the table rather than
hardcoded. 062 already used this pattern and passed on 32-bit.
The same change is in the REL15..REL19 back-branch patches, which ship
their own copy of the test.
0001 (the torn-page redo fix) stands alone and is back-patchable;
0002-0004 are master only.
-greg
Attachments: download all (5 files, .tar.gz)
v12-0004-Remove-REGBUF_NO_CHANGE.patch (text/x-patch, 5.2K) download
From c5bb496ecb507dfd9619a78c67246b03c5999646 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:17:46 -0400
Subject: [PATCH v12 4/4] Remove REGBUF_NO_CHANGE
With the previous commits, the hash index AM no longer registers any
pin-only or otherwise-unchanged buffer, so REGBUF_NO_CHANGE has no users
left. Remove the flag and restore the invariant that every registered
buffer is content-locked and dirty: XLogRegisterBuffer() asserts it
unconditionally again.
This also reverts the defensive measures added in 27caf4ca5ae5, which
let a REGBUF_NO_CHANGE buffer skip the full-page image forced by
wal_consistency_checking: XLogRecordAssemble() no longer special-cases
the flag, and verifyBackupPageConsistency() again asserts that a
registered block carries an image. 27caf4ca5ae5 remains in the back
branches, where this hash rework is not applied.
Discussion: https://postgr.es/m/055bb33c-bccc-bc1d-c2f8-8598534448ac@gmail.com
---
src/backend/access/transam/README | 5 ----
src/backend/access/transam/xloginsert.c | 28 ++++++-----------------
src/backend/access/transam/xlogrecovery.c | 7 +-----
src/include/access/xloginsert.h | 3 ---
4 files changed, 8 insertions(+), 35 deletions(-)
diff --git a/src/backend/access/transam/README b/src/backend/access/transam/README
index 595afa01fa7..231106270fd 100644
--- a/src/backend/access/transam/README
+++ b/src/backend/access/transam/README
@@ -586,11 +586,6 @@ void XLogRegisterBuffer(uint8 block_id, Buffer buf, uint8 flags);
XLogRegisterBufData() is included in the WAL record even if a full-page
image is taken.
- The REGBUF_NO_CHANGE flag indicates that the buffer is registered without
- being modified by this record, and possibly without an exclusive content
- lock. wal_consistency_checking does not force a full-page image for such
- a buffer.
-
void XLogRegisterData(const void *data, int len);
XLogRegisterData is used to include arbitrary data in the WAL record. If
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index cd3359434e1..2d031e38594 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -257,22 +257,13 @@ XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Assert(begininsert_called);
/*
- * Ordinarily, the buffer should be exclusive-locked (or share-exclusive
- * in case of hint bits) and marked dirty before we get here, otherwise we
- * could end up violating one of the rules in access/transam/README.
- *
- * Some callers intentionally register a clean page and never update that
- * page's LSN; in that case they can pass the flag REGBUF_NO_CHANGE to
- * bypass these checks.
+ * The buffer should be exclusive-locked (or share-exclusive in case of
+ * hint bits) and marked dirty before we get here, otherwise we could end
+ * up violating one of the rules in access/transam/README.
*/
-#ifdef USE_ASSERT_CHECKING
- if (!(flags & REGBUF_NO_CHANGE))
- {
- Assert(BufferIsDirty(buffer));
- Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
- BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
- }
-#endif
+ Assert(BufferIsDirty(buffer));
+ Assert(BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_EXCLUSIVE) ||
+ BufferIsLockedByMeInMode(buffer, BUFFER_LOCK_SHARE_EXCLUSIVE));
if (block_id >= max_registered_block_id)
{
@@ -722,13 +713,8 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
- *
- * Do not force an image for a REGBUF_NO_CHANGE buffer.
*/
- if (regbuf->flags & REGBUF_NO_CHANGE)
- include_image = needs_backup;
- else
- include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
+ include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
if (include_image)
{
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index e091a3e178b..1b2c9cc78e9 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -2487,12 +2487,7 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- /*
- * Blocks registered with REGBUF_NO_CHANGE may have no image, see
- * XLogRecordAssemble(). Nothing to compare for these.
- */
- if (!XLogRecHasBlockImage(record, block_id))
- continue;
+ Assert(XLogRecHasBlockImage(record, block_id));
if (XLogRecBlockImageApply(record, block_id))
{
diff --git a/src/include/access/xloginsert.h b/src/include/access/xloginsert.h
index 86264564ebb..ddb1a85db59 100644
--- a/src/include/access/xloginsert.h
+++ b/src/include/access/xloginsert.h
@@ -38,9 +38,6 @@
* will be skipped) */
#define REGBUF_KEEP_DATA 0x10 /* include data even if a full-page image
* is taken */
-#define REGBUF_NO_CHANGE 0x20 /* intentionally register clean buffer; no
- * image is forced for WAL consistency
- * checking */
/* prototypes for public functions in xloginsert.c: */
extern void XLogBeginInsert(void);
--
2.54.0
v12-0001-Fix-hash-index-redo-reading-a-torn-primary-bucke.patch (text/x-patch, 18.1K) download
From c079e6d794e1a70c30af84cc9b2e71edbd7aafcf Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 12 Nov 2026 12:58:59 +0000
Subject: [PATCH v12 1/4] Fix hash index redo reading a torn primary bucket
page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 43 +++-
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_torn_primary_page.pl | 243 ++++++++++++++++++
5 files changed, 280 insertions(+), 11 deletions(-)
create mode 100644 src/test/recovery/t/061_hash_torn_primary_page.pl
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..e1318bf97db 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -494,10 +495,18 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -621,10 +630,18 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -852,10 +869,18 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock on the primary bucket page serializes replay
+ * against scans on a hot standby, which pin the page for their whole
+ * duration. Scans can run only once hot standby accepts queries, so
+ * until then we need not read or lock the page. Skipping the read
+ * also sidesteps a torn copy of the page whose repairing full-page
+ * image comes later in the WAL: that hazard exists only before
+ * consistency is reached, and queries are accepted only after that,
+ * so once HotStandbyActiveInReplay() is true any earlier image has
+ * already been replayed. We do not use the page contents here.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..e091a3e178b 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -390,7 +390,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4589,7 +4588,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 8786b6d3a8e..11d3eadef3e 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -216,6 +216,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..785f2d820b1 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_torn_primary_page.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
new file mode 100644
index 00000000000..be9aea4913e
--- /dev/null
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -0,0 +1,243 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test redo of a hash VACUUM record that reads a torn primary bucket page, whose
+# repairing full-page image comes later in the WAL, in a standby started from a
+# base backup and in crash recovery. Data checksums must be on, so that the
+# torn page is detected.
+
+use strict;
+use warnings FATAL => 'all';
+
+use File::Path qw(rmtree);
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+# Tear a block of a relation file, as a torn write does: keep the first half of
+# the block and overwrite the second half with random bytes, so that its
+# checksum does not match.
+sub tear_page
+{
+ my ($path, $pblk, $bs) = @_;
+
+ open(my $fh, '+<:raw', $path) or die "could not open $path: $!";
+ sysseek($fh, $pblk * $bs + $bs / 2, 0) or die "seek: $!";
+ my $junk = join('', map { chr(int(rand(256))) } 1 .. $bs / 2);
+ syswrite($fh, $junk) == $bs / 2 or die "write: $!";
+ close($fh);
+}
+
+my $primary = PostgreSQL::Test::Cluster->new('primary');
+$primary->init(allows_streaming => 1);
+$primary->append_conf(
+ 'postgresql.conf', qq{
+autovacuum = off
+fsync = off
+full_page_writes = on
+checkpoint_timeout = 1h
+});
+$primary->start;
+
+is($primary->safe_psql('postgres', 'SHOW data_checksums'),
+ 'on', 'premise: data checksums are on');
+
+# One bucket receives every key: a primary bucket page and one overflow page.
+# fillfactor keeps the heap row count per page fixed across architectures, and
+# vacuuming the empty table first makes hashbuild() start the index with the
+# minimum two buckets, so the layout does not depend on pointer width.
+$primary->safe_psql('postgres', 'CREATE EXTENSION pageinspect');
+$primary->safe_psql(
+ 'postgres', q{
+CREATE TABLE t (k int) WITH (autovacuum_enabled = false, fillfactor = 100);
+VACUUM t;
+CREATE INDEX t_i ON t USING hash (k);
+INSERT INTO t SELECT 1 FROM generate_series(1, 600);
+});
+my $relpath = $primary->safe_psql('postgres',
+ q{SELECT pg_relation_filepath('t_i')});
+my $bs = $primary->safe_psql('postgres', 'SHOW block_size');
+
+# Start a low-level backup, which does a checkpoint, and copy the files.
+my $backup_name = 'torn';
+my $backup_dir = $primary->backup_dir . '/' . $backup_name;
+my $psql = $primary->background_psql('postgres');
+$psql->query_safe("SET client_min_messages TO WARNING");
+$psql->set_query_timer_restart;
+$psql->query_safe("select pg_backup_start('torn primary page', true)");
+my $redo = $primary->safe_psql('postgres',
+ 'SELECT redo_lsn FROM pg_control_checkpoint()');
+
+# Copy the data directory of the running server, as a backup does. Remove what
+# must not be in a backup, as pg_basebackup does: postmaster.pid, which would
+# make a server started from the copy think that the primary's postmaster is
+# still running, postmaster.opts, which only records how the primary was
+# started, and the WAL segments, which are copied at an arbitrary moment, and
+# which the standby gets by streaming, starting at the redo pointer of the
+# backup. The server expects pg_wal to exist, so create it empty.
+PostgreSQL::Test::RecursiveCopy::copypath($primary->data_dir, $backup_dir);
+unlink("$backup_dir/postmaster.pid")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.pid");
+unlink("$backup_dir/postmaster.opts")
+ or BAIL_OUT("unable to unlink $backup_dir/postmaster.opts");
+rmtree("$backup_dir/pg_wal")
+ or BAIL_OUT("unable to unlink contents of $backup_dir/pg_wal");
+mkdir("$backup_dir/pg_wal");
+
+# While the backup is in progress: delete exactly the index entries that live
+# on the overflow pages, so VACUUM removes dead entries only from the overflow
+# chain and never from the primary bucket page. VACUUM then logs an
+# XLOG_HASH_DELETE for the overflow page while holding the primary bucket page
+# pin-only (not registered), and the squeeze that follows is the first record
+# to change the primary page since the backup checkpoint, so it carries the
+# full-page image that repairs the torn page on replay. Keying the delete off
+# the actual page contents keeps this true regardless of how many entries fit
+# on a page, which varies by architecture.
+$primary->safe_psql(
+ 'postgres', q{
+DELETE FROM t WHERE ctid IN (
+ SELECT i.ctid
+ FROM generate_series(1, pg_relation_size('t_i') / current_setting('block_size')::int - 1) b
+ CROSS JOIN LATERAL hash_page_items(get_raw_page('t_i', b)) i
+ WHERE hash_page_type(get_raw_page('t_i', b)) = 'overflow');
+VACUUM t;
+});
+
+# The number of live entries left, which the index must return after recovery.
+# It depends on how many entries fit on a page, so read it rather than assume.
+my $live = $primary->safe_psql('postgres', 'SELECT count(*) FROM t WHERE k = 1');
+
+# Read the Hash records written since the checkpoint.
+my $end_lsn =
+ $primary->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$primary->safe_psql('postgres', 'SELECT pg_switch_wal()');
+
+# The first and the last WAL segment of the range.
+my $start_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$redo')");
+my $end_seg =
+ $primary->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Dump the Hash records from the redo pointer of the backup to the end of the
+# WAL written so far. The output is parsed below.
+my ($stdout, $stderr);
+IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $primary->data_dir . '/pg_wal',
+ '--start' => $redo,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => \$stdout,
+ '2>' => \$stderr);
+my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
+
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
+# block 1, the page that is changed.
+my $pblk;
+for my $r (@records)
+{
+ if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
+ && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ {
+ $pblk = $1;
+ last;
+ }
+}
+ok(defined $pblk, 'premise: found the primary bucket page')
+ or diag $stdout, $stderr;
+
+# The DELETE for an overflow page has to come before the first full-page image
+# of the primary page.
+my ($idx_delete) =
+ grep { $records[$_] =~ /desc: DELETE .*is_primary F/ } 0 .. $#records;
+ok(defined $idx_delete, 'premise: VACUUM wrote a DELETE for an overflow page')
+ or diag $stdout, $stderr;
+
+my ($idx_fpi) =
+ defined $pblk
+ ? grep { $records[$_] =~ /blkref #\d+: rel \S+ blk $pblk FPW/ }
+ 0 .. $#records
+ : ();
+ok(defined $idx_fpi,
+ 'premise: the primary page got a full-page image after the checkpoint')
+ or diag $stdout, $stderr;
+if (defined $idx_delete && defined $idx_fpi)
+{
+ cmp_ok($idx_delete, '<', $idx_fpi,
+ 'premise: the DELETE comes before the image of the primary page');
+}
+
+# Tear the copy of the primary page in the backup.
+tear_page("$backup_dir/$relpath", $pblk, $bs) if defined $pblk;
+
+# End the backup, and save backup_label into the backup.
+my $backup_label = $psql->query_safe("select labelfile from pg_backup_stop()");
+$psql->quit;
+open(my $fh, '>', "$backup_dir/backup_label")
+ or BAIL_OUT("unable to create $backup_dir/backup_label: $!");
+print $fh $backup_label;
+close($fh);
+
+###############################################################################
+# A standby started from the backup
+###############################################################################
+
+# Replay starts at the redo pointer of the backup, replays the DELETE for the
+# overflow page first, and reaches the consistency point only after the end of
+# the backup, after the full-page image of the primary page.
+my $standby = PostgreSQL::Test::Cluster->new('standby');
+$standby->init_from_backup($primary, $backup_name, has_streaming => 1);
+$standby->append_conf('postgresql.conf', 'hot_standby = on');
+
+my $started = $standby->start(fail_ok => 1);
+ok($started, 'standby: the standby starts');
+if ($started)
+{
+ $primary->wait_for_catchup($standby);
+ is( $standby->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ $live,
+ 'standby: the hash index gives the right result');
+ $standby->stop;
+}
+else
+{
+ my $log = slurp_file($standby->logfile);
+ diag("standby: the standby did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo|consistent recovery/ } split(/^/m, $log)));
+}
+
+###############################################################################
+# Crash recovery of the primary
+###############################################################################
+
+# There was no checkpoint since the one of the backup, so crash recovery
+# replays the same records from the same redo pointer. Tear the primary's own
+# copy of the page.
+$primary->stop('immediate');
+tear_page($primary->data_dir . '/' . $relpath, $pblk, $bs) if defined $pblk;
+
+$started = $primary->start(fail_ok => 1);
+ok($started, 'crash recovery: the server starts');
+if ($started)
+{
+ is( $primary->safe_psql(
+ 'postgres',
+ q{SET enable_seqscan = off; SET enable_bitmapscan = off;
+ SELECT count(*) FROM t WHERE k = 1}),
+ $live,
+ 'crash recovery: the hash index gives the right result');
+}
+else
+{
+ my $log = slurp_file($primary->logfile);
+ diag("crash recovery: the server did not start; the log has:\n"
+ . join('', grep { /invalid page|FATAL|WAL redo/ } split(/^/m, $log)));
+}
+
+done_testing();
--
2.54.0
v12-0002-Don-t-register-pin-only-primary-bucket-pages-in-.patch (text/x-patch, 25.2K) download
From 875222fcf3405d8eddfba646a3b6b28550e3510c Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v12 2/4] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that no scan on a hot standby is in progress in the bucket, and
none can start, while tuples are removed or moved. That lock was
obtained by registering the page (pin-only) with REGBUF_NO_CHANGE; redo
never reads data from the block, the registration existed only for the
lock. That broke the rule that a registered buffer is one the caller
holds exclusively locked and dirty, and under wal_consistency_checking
it forced a full-page image of a page a concurrent inserter could still
modify, so the record CRC was computed over shifting data.
Stop registering the primary bucket page when the record does not change
it. When the page is not one of the pages the record changes, the
operation holds only a pin on it, so the record carries the page's block
number in its main data and replay reads that block and takes a cleanup
lock on it directly, at the same point and in the same order as before.
The block number is appended only in that case, so the records are no
larger than before in the common case where the primary bucket page is
registered.
After this change hash registers only buffers it holds exclusively
locked and dirty, and there are no REGBUF_NO_CHANGE users left.
The three record formats change, so bump XLOG_PAGE_MAGIC; master only.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/auNs8b_vS2OPdTL8@floki
---
src/backend/access/hash/README | 9 ++
src/backend/access/hash/hash.c | 18 ++-
src/backend/access/hash/hash_xlog.c | 132 ++++++++++--------
src/backend/access/hash/hashovfl.c | 99 ++++++-------
src/include/access/hash_xlog.h | 37 +++--
src/include/access/xlog_internal.h | 2 +-
.../recovery/t/061_hash_torn_primary_page.pl | 6 +-
7 files changed, 162 insertions(+), 141 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record then carries its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..9a919654ce5 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -909,19 +909,17 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * Replay must take a cleanup lock on the primary bucket page
+ * to serialize with scans on a hot standby. If buf is an
+ * overflow page, the unchanged primary page is held only by a
+ * pin, so append its block number instead of registering it.
+ * Otherwise block 0 identifies the primary page.
*/
if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
- XLogRegisterBufData(1, deletable,
+ XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_DELETE);
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e1318bf97db..f7a30c8ea90 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -470,6 +470,45 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on an unregistered primary bucket page, whose block
+ * number is stored in the record's main data. This serializes replay against
+ * scans on a hot standby. block_id must identify a registered block of the
+ * same index.
+ */
+static Buffer
+hash_xlog_lock_primary_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ BlockNumber bucket_blkno;
+ Buffer buf;
+
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
+ /*
+ * The cleanup lock on the primary bucket page serializes replay against
+ * scans on a hot standby, which pin the page for their whole duration.
+ * Scans can run only once hot standby accepts queries, so until then we
+ * need not read or lock the page. Skipping the read also sidesteps a torn
+ * copy of the page whose repairing full-page image comes later in the WAL:
+ * that hazard exists only before consistency is reached, and queries are
+ * accepted only after that, so once HotStandbyActiveInReplay() is true any
+ * earlier image has already been replayed. Redo never uses the page's
+ * contents here in any case.
+ */
+ if (!HotStandbyActiveInReplay())
+ return InvalidBuffer;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -491,24 +530,12 @@ hash_xlog_move_page_contents(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
- */
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashMovePageContents);
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
}
/* replay the record for adding entries in overflow buffer */
@@ -520,7 +547,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
Size datalen;
uint16 ninserted = 0;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -559,13 +586,13 @@ hash_xlog_move_page_contents(XLogReaderState *record)
}
/* replay the record for deleting entries from overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &deletebuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &deletebuf) == BLK_NEEDS_REDO)
{
Page page;
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 2, &len);
+ ptr = XLogRecGetBlockData(record, 1, &len);
page = BufferGetPage(deletebuf);
@@ -626,25 +653,26 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
- else
{
/*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
+ * If the primary bucket page is modified, it is registered as block
+ * 0 and read for redo. Otherwise, acquire its cleanup lock
+ * separately.
*/
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (XLogRecHasBlockRef(record, 0))
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
+ else
+ {
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
+ action = BLK_NOTFOUND;
+ }
+ }
+ else
+ {
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
else
action = BLK_NOTFOUND;
}
@@ -659,7 +687,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint16 ninserted = 0;
bool mod_wbuf = false;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -725,7 +753,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
}
/* replay the record for initializing overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &ovflbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &ovflbuf) == BLK_NEEDS_REDO)
{
Page ovflpage;
HashPageOpaque ovflopaque;
@@ -750,7 +778,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/* replay the record for page previous to the freed overflow page */
if (!xldata->is_prev_bucket_same_wrt &&
- XLogReadBufferForRedo(record, 3, &prevbuf) == BLK_NEEDS_REDO)
+ XLogReadBufferForRedo(record, 2, &prevbuf) == BLK_NEEDS_REDO)
{
Page prevpage = BufferGetPage(prevbuf);
HashPageOpaque prevopaque = HashPageGetOpaque(prevpage);
@@ -764,11 +792,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(prevbuf);
/* replay the record for page next to the freed overflow page */
- if (XLogRecHasBlockRef(record, 4))
+ if (XLogRecHasBlockRef(record, 3))
{
Buffer nextbuf;
- if (XLogReadBufferForRedo(record, 4, &nextbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 3, &nextbuf) == BLK_NEEDS_REDO)
{
Page nextpage = BufferGetPage(nextbuf);
HashPageOpaque nextopaque = HashPageGetOpaque(nextpage);
@@ -795,7 +823,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* index updates can be happening concurrently.
*/
/* replay the record for bitmap page */
- if (XLogReadBufferForRedo(record, 5, &mapbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 4, &mapbuf) == BLK_NEEDS_REDO)
{
Page mappage = BufferGetPage(mapbuf);
uint32 *freep = NULL;
@@ -805,7 +833,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
freep = HashPageGetBitmap(mappage);
- data = XLogRecGetBlockData(record, 5, &datalen);
+ data = XLogRecGetBlockData(record, 4, &datalen);
bitmap_page_bit = (uint32 *) data;
CLRBIT(freep, *bitmap_page_bit);
@@ -817,11 +845,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(mapbuf);
/* replay the record for meta page */
- if (XLogRecHasBlockRef(record, 6))
+ if (XLogRecHasBlockRef(record, 5))
{
Buffer metabuf;
- if (XLogReadBufferForRedo(record, 6, &metabuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 5, &metabuf) == BLK_NEEDS_REDO)
{
HashMetaPage metap;
Page page;
@@ -829,7 +857,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint32 *firstfree_ovflpage;
Size datalen;
- data = XLogRecGetBlockData(record, 6, &datalen);
+ data = XLogRecGetBlockData(record, 5, &datalen);
firstfree_ovflpage = (uint32 *) data;
page = BufferGetPage(metabuf);
@@ -865,24 +893,12 @@ hash_xlog_delete(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_primary_bucket_page)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * The cleanup lock on the primary bucket page serializes replay
- * against scans on a hot standby, which pin the page for their whole
- * duration. Scans can run only once hot standby accepts queries, so
- * until then we need not read or lock the page. Skipping the read
- * also sidesteps a torn copy of the page whose repairing full-page
- * image comes later in the WAL: that hazard exists only before
- * consistency is reached, and queries are accepted only after that,
- * so once HotStandbyActiveInReplay() is true any earlier image has
- * already been replayed. We do not use the page contents here.
- */
- if (HotStandbyActiveInReplay())
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashDelete);
- action = XLogReadBufferForRedo(record, 1, &deletebuf);
+ action = XLogReadBufferForRedo(record, 0, &deletebuf);
}
/* replay the record for deleting entries in bucket page */
@@ -891,7 +907,7 @@ hash_xlog_delete(XLogReaderState *record)
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 1, &len);
+ ptr = XLogRecGetBlockData(record, 0, &len);
page = BufferGetPage(deletebuf);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..35f214767bd 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,6 +660,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
@@ -667,45 +672,26 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Replay needs the primary bucket block number to acquire a cleanup
+ * lock. Register it as block 0 when it is modified; otherwise append
+ * its block number to the record.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- if (nitups > 0)
- {
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
+ if (mod_wbuf)
{
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(0, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
+ }
}
- XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(1, ovflbuf, REGBUF_STANDARD);
/*
* If prevpage and the writepage (block in which we are moving tuples
@@ -714,18 +700,18 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* writepage.
*/
if (BufferIsValid(prevbuf) && !is_prev_bucket_same_wrt)
- XLogRegisterBuffer(3, prevbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(2, prevbuf, REGBUF_STANDARD);
if (BufferIsValid(nextbuf))
- XLogRegisterBuffer(4, nextbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(3, nextbuf, REGBUF_STANDARD);
- XLogRegisterBuffer(5, mapbuf, REGBUF_STANDARD);
- XLogRegisterBufData(5, &bitmapbit, sizeof(uint32));
+ XLogRegisterBuffer(4, mapbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(4, &bitmapbit, sizeof(uint32));
if (update_metap)
{
- XLogRegisterBuffer(6, metabuf, REGBUF_STANDARD);
- XLogRegisterBufData(6, &metap->hashm_firstfree, sizeof(uint32));
+ XLogRegisterBuffer(5, metabuf, REGBUF_STANDARD);
+ XLogRegisterBufData(5, &metap->hashm_firstfree, sizeof(uint32));
}
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SQUEEZE_PAGE);
@@ -966,10 +952,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -998,25 +986,22 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, itup_offsets,
nitups * sizeof(OffsetNumber));
for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
- XLogRegisterBuffer(2, rbuf, REGBUF_STANDARD);
- XLogRegisterBufData(2, deletable,
+ XLogRegisterBuffer(1, rbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_MOVE_PAGE_CONTENTS);
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..0bb0d0590f5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,9 +129,13 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing moved tuples
- * Backup Blk 2: page from which tuples will be removed
+ * Backup Blk 0: page containing moved tuples
+ * Backup Blk 1: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
@@ -149,13 +153,18 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
- * Backup Blk 2: freed overflow page
- * Backup Blk 3: page previous to the freed overflow page
- * Backup Blk 4: page next to the freed overflow page
- * Backup Blk 5: bitmap page containing info of freed overflow page
- * Backup Blk 6: meta page
+ * Backup Blk 0: page containing tuples moved from freed overflow page, if
+ * it is modified
+ * Backup Blk 1: freed overflow page
+ * Backup Blk 2: page previous to the freed overflow page
+ * Backup Blk 3: page next to the freed overflow page
+ * Backup Blk 4: bitmap page containing info of freed overflow page
+ * Backup Blk 5: meta page
+ *
+ * The primary bucket page is registered only as block 0, when it is the
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
@@ -179,8 +188,12 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page from which tuples are deleted
+ * Backup Blk 0: page from which tuples are deleted
+ *
+ * If block 0 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
diff --git a/src/test/recovery/t/061_hash_torn_primary_page.pl b/src/test/recovery/t/061_hash_torn_primary_page.pl
index be9aea4913e..b2358dc37b2 100644
--- a/src/test/recovery/t/061_hash_torn_primary_page.pl
+++ b/src/test/recovery/t/061_hash_torn_primary_page.pl
@@ -134,13 +134,13 @@ IPC::Run::run(
'2>' => \$stderr);
my @records = grep { /^rmgr: Hash/ } split(/^(?=rmgr: )/m, $stdout);
-# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T has it as
-# block 1, the page that is changed.
+# The primary page: a DELETE or SQUEEZE_PAGE marked is_primary T changes it, so
+# it is the first block reference of the record.
my $pblk;
for my $r (@records)
{
if ($r =~ /desc: (?:DELETE|SQUEEZE_PAGE) .*is_primary T/
- && $r =~ /blkref #1: rel \S+ blk (\d+)/)
+ && $r =~ /blkref #0: rel \S+ blk (\d+)/)
{
$pblk = $1;
last;
--
2.54.0
v12-0003-Add-a-recovery-test-for-the-hash-WAL-pin-only-bu.patch (text/x-patch, 12.0K) download
From cd6ea23f24c9ced6455c38823c3076707c41a91c Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v12 3/4] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/062_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 ++
src/test/recovery/meson.build | 1 +
.../recovery/t/062_hash_vacuum_insert_crc.pl | 191 ++++++++++++++++++
3 files changed, 214 insertions(+)
create mode 100644 src/test/recovery/t/062_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index 785f2d820b1..be397ea20ed 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -70,6 +70,7 @@ tests += {
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
't/061_hash_torn_primary_page.pl',
+ 't/062_hash_vacuum_insert_crc.pl',
],
},
}
diff --git a/src/test/recovery/t/062_hash_vacuum_insert_crc.pl b/src/test/recovery/t/062_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..89f7611af12
--- /dev/null
+++ b/src/test/recovery/t/062_hash_vacuum_insert_crc.pl
@@ -0,0 +1,191 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# The first and the last WAL segment of the range. With only --path, pg_waldump
+# takes the WAL segment size from the first file readdir() returns, which can be
+# a zero-filled, unused segment, and then fails with "invalid WAL segment size".
+# Naming the segments makes it read the size from the first of them.
+my $start_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$start_lsn')");
+my $end_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.54.0
back-patches.tgz.nocfbot (application/octet-stream, 7.4K) download
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-16 10:52 ` Amit Kapila <amit.kapila16@gmail.com>
2026-11-16 11:30 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-17 11:20 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
0 siblings, 2 replies; 34+ messages in thread
From: Amit Kapila @ 2026-11-16 10:52 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; +Cc: Hayato Kuroda <kuroda.hayato@fujitsu.com>; vignesh C <vignesh21@gmail.com>; Joao Rito <joaovictor.rito@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
On Sun, Nov 15, 2026 at 2:06 AM Greg Burd <greg@burd.me> wrote:
>
> Hayato, vignesh, Joao,
>
> v12 attached. Same series as v11, with one fix: the new torn-page test
> failed CI on 32-bit, and this corrects it. Code is unchanged from v11.
>
I don't think we want to commit the test to create a torn-page as it
appears complex and not sure if we have any other similar test though
it is good to use for testing the fix. I suggest let's first commit
the fix for torn-page reads issue (Fix hash index redo reading a torn
primary bucket page) as that needs to be backpatched. Once that is
committed, we can look at HEAD-only code improvements separately. If
we agree on this, can one of you separate out the test and share
bug-fix patches?
--
With Regards,
Amit Kapila.
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
@ 2026-11-16 11:30 ` Greg Burd <greg@burd.me>
1 sibling, 0 replies; 34+ messages in thread
From: Greg Burd @ 2026-11-16 11:30 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Hayato Kuroda <kuroda.hayato@fujitsu.com>; vignesh C <vignesh21@gmail.com>; Joao Rito <joaovictor.rito@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
On Monday, November 16th, 2026 at 5:53 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Sun, Nov 15, 2026 at 2:06 AM Greg Burd <greg@burd.me> wrote:
> >
> > Hayato, vignesh, Joao,
> >
> > v12 attached. Same series as v11, with one fix: the new torn-page test
> > failed CI on 32-bit, and this corrects it. Code is unchanged from v11.
> >
>
> I don't think we want to commit the test to create a torn-page as it
> appears complex and not sure if we have any other similar test though
> it is good to use for testing the fix. I suggest let's first commit
> the fix for torn-page reads issue (Fix hash index redo reading a torn
> primary bucket page) as that needs to be backpatched. Once that is
> committed, we can look at HEAD-only code improvements separately. If
> we agree on this, can one of you separate out the test and share
> bug-fix patches?
Hey Amit,
I was thinking the same thing, I'll take a bit of time today and stage it
as such.
best.
-greg
> --
> With Regards,
> Amit Kapila.
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
@ 2026-11-17 11:20 ` vignesh C <vignesh21@gmail.com>
2026-11-17 20:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
1 sibling, 1 reply; 34+ messages in thread
From: vignesh C @ 2026-11-17 11:20 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Greg Burd <greg@burd.me>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; Joao Rito <joaovictor.rito@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
On Mon, 16 Nov 2026 at 16:23, Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Sun, Nov 15, 2026 at 2:06 AM Greg Burd <greg@burd.me> wrote:
> >
> > Hayato, vignesh, Joao,
> >
> > v12 attached. Same series as v11, with one fix: the new torn-page test
> > failed CI on 32-bit, and this corrects it. Code is unchanged from v11.
> >
>
> I don't think we want to commit the test to create a torn-page as it
> appears complex and not sure if we have any other similar test though
> it is good to use for testing the fix. I suggest let's first commit
> the fix for torn-page reads issue (Fix hash index redo reading a torn
> primary bucket page) as that needs to be backpatched. Once that is
> committed, we can look at HEAD-only code improvements separately. If
> we agree on this, can one of you separate out the test and share
> bug-fix patches?
Thanks, here is the updated v13 version patch to remove the test.
Apart from this, the following changes were done:
a) Retain the comment which was there to indicate we skip checking
return value of XLogReadBufferForRedoExtended:
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the
purpose of reading
+ * bucketbuf is to ensure a cleanup lock on
primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record,
0, RBM_NORMAL, true, &bucketbuf);
+ }
b) Improved the comments to mention about how
XLogReadBufferForRedoExtended is not required when hot standby is
active and how torn page problem will resolved by later wal record:
/*
- * we don't care for return value as the purpose of
reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is
active, because
+ * scans cannot run before that. Skipping the read
also avoids a torn
+ * copy of the primary page. This record does not
modify that page, so
+ * it has no full-page image of it. In crash recovery,
or on a standby
+ * started from a base backup, the page on disk can be
torn and the
+ * image that repairs it can come later in the WAL.
*/
c) Added Amit and Joao Rito as reviewers who also reviewed the patch.
The v13-0001-Fix-hash-index-redo-reading-a-torn-primary-bucke.patch
patch applies till PG17 branch and
v13_REL16-0001-Fix-hash-index-redo-reading-a-torn-primary.patch
applies in PG16 and PG15 branches.
Regards,
Vignesh
Attachments: download all (2 files, .tar.gz)
v13_REL16-0001-Fix-hash-index-redo-reading-a-torn-primary.patch (application/octet-stream, 7.6K) download
From 3ca6f01207769ab53524f4341a66f0cf3984a61d Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Tue, 17 Nov 2026 16:38:34 +0530
Subject: [PATCH v13_REL16] Fix hash index redo reading a torn primary bucket
page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Joao Rito <joaovictor.rito@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 52 +++++++++++++++++++----
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
3 files changed, 45 insertions(+), 11 deletions(-)
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index cd9617533c2..f2edf15f2b4 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -19,6 +19,7 @@
#include "access/hash_xlog.h"
#include "access/transam.h"
#include "access/xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "miscadmin.h"
#include "storage/procarray.h"
@@ -499,10 +500,21 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -627,10 +639,21 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -839,10 +862,21 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 2bc615a691b..7f9ec6d8075 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -441,7 +441,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, int emode, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4528,7 +4527,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 7737f9e2cf0..0c25471c2e5 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -136,6 +136,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
--
2.55.0
v13-0001-Fix-hash-index-redo-reading-a-torn-primary-bucke.patch (application/octet-stream, 7.6K) download
From b9f57580de5eae940dd7acd1b439d20d5ce1e6fc Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Tue, 17 Nov 2026 09:10:56 +0530
Subject: [PATCH v13] Fix hash index redo reading a torn primary bucket page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Joao Rito <joaovictor.rito@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
Backpatch-through: 15
---
src/backend/access/hash/hash_xlog.c | 52 +++++++++++++++++++----
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
3 files changed, 45 insertions(+), 11 deletions(-)
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..46047c6ea27 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -494,10 +495,21 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -621,10 +633,21 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -852,10 +875,21 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..e091a3e178b 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -390,7 +390,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4589,7 +4588,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 8786b6d3a8e..11d3eadef3e 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -216,6 +216,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
--
2.55.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-17 11:20 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
@ 2026-11-17 20:21 ` Greg Burd <greg@burd.me>
2026-11-18 07:13 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
0 siblings, 1 reply; 34+ messages in thread
From: Greg Burd @ 2026-11-17 20:21 UTC (permalink / raw)
To: vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; +Cc: Hayato Kuroda <kuroda.hayato@fujitsu.com>; Joao Rito <joaovictor.rito@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
Amit, Vignesh,
Agreed, and thanks Vignesh for splitting it out. v13 is what I had in
mind: the torn-page read fix on its own, backpatchable, with the
recovery test and the HEAD-only rework (dropping the pin-only
registration, removing REGBUF_NO_CHANGE) left for a separate commit on
master once this is in.
I confirmed the two patches apply where Vignesh said: v13-0001 from
master through PG17, and v13_REL16-0001 on PG16 and PG15.
I am re-attaching Vignesh's two patches unchanged so this message has
the reviewed set in one place. No change from his v13.
For the follow-up on master I will post the test and the pin-only rework
as their own thread-continuation once the fix lands, including the
arch-independent torn-page test (it keys the deletion off the actual
overflow-page contents with pageinspect, so it holds on 32-bit, and
writes backup_label in binary mode so it holds on Windows). No need to
hold the fix for that.
-greg
Attachments: download all (2 files, .tar.gz)
v13-0001-Fix-hash-index-redo-reading-a-torn-primary-bucket.patch (text/x-patch, 7.8K) download
From b9f57580de5eae940dd7acd1b439d20d5ce1e6fc Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Tue, 17 Nov 2026 09:10:56 +0530
Subject: [PATCH v13] Fix hash index redo reading a torn primary bucket page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Joao Rito <joaovictor.rito@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
Backpatch-through: 15
---
src/backend/access/hash/hash_xlog.c | 52 +++++++++++++++++++----
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
3 files changed, 45 insertions(+), 11 deletions(-)
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index e9a2b9aa9a7..46047c6ea27 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -17,6 +17,7 @@
#include "access/bufmask.h"
#include "access/hash.h"
#include "access/hash_xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "storage/standby.h"
@@ -494,10 +495,21 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -621,10 +633,21 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 1, &writebuf);
@@ -852,10 +875,21 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 52ac6d58423..e091a3e178b 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -390,7 +390,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4589,7 +4588,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 8786b6d3a8e..11d3eadef3e 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -216,6 +216,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
--
2.55.0
v13_REL16-0001-Fix-hash-index-redo-reading-a-torn-primary.patch (text/x-patch, 7.8K) download
From 3ca6f01207769ab53524f4341a66f0cf3984a61d Mon Sep 17 00:00:00 2001
From: Vignesh C <vignesh21@gmail.com>
Date: Tue, 17 Nov 2026 16:38:34 +0530
Subject: [PATCH v13_REL16] Fix hash index redo reading a torn primary bucket
page
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE reads the primary bucket page only to take a
cleanup lock on it, so that no scan on a hot standby runs in the bucket
while tuples are removed or moved. VACUUM holds only a pin on that page,
so the record does not modify it and carries no full-page image of it;
redo reads it from disk with RBM_NORMAL.
If the page is torn on disk and the record that repairs it with a
full-page image comes later in the WAL, recovery fails when it reaches
one of these records before the image, because the RBM_NORMAL read of
the torn page raises "invalid page". This happens both in crash
recovery (the image is in WAL generated after the last checkpoint) and
on a standby started from a base backup whose copy of the page is torn
(the image is in WAL generated during the backup).
Robert Haas noted this torn-page hazard during the original hash WAL
work in 2017; redo was switched to XLogReadBufferForRedoExtended() so it
restores an image when the record has one, but these records register
the primary bucket page pin-only with REGBUF_NO_IMAGE, so there is no
image to restore and the RBM_NORMAL read still reaches the torn page.
The cleanup lock matters only to serialize against hot-standby scans,
which can run only once the standby accepts queries, that is once
recovery has reached consistency. Until then the read and lock are
unnecessary, so skip them when HotStandbyActiveInReplay() is false.
That also avoids reading the page in the window where its torn on-disk
copy has not yet been repaired, since the repairing image always
precedes the consistency point. nbtree and gist already gate redo
cleanup-lock work on the hot-standby state for the same reason.
Reported-by: shihao zhong <zhong950419@gmail.com>
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Joao Rito <joaovictor.rito@gmail.com>
Discussion: https://postgr.es/m/CAGRkXqT_AiwcsWZg5hnR1L2oWO8UpQpkL0iAjoZR+bey=GOWaQ@mail.gmail.com
Discussion: https://postgr.es/m/CAA4eK1LwZk0MaK0LncZz6hsqcHnamfJB47nA8xuwRp4CyLFKzw@mail.gmail.com
---
src/backend/access/hash/hash_xlog.c | 52 +++++++++++++++++++----
src/backend/access/transam/xlogrecovery.c | 3 +-
src/include/access/xlogrecovery.h | 1 +
3 files changed, 45 insertions(+), 11 deletions(-)
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index cd9617533c2..f2edf15f2b4 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -19,6 +19,7 @@
#include "access/hash_xlog.h"
#include "access/transam.h"
#include "access/xlog.h"
+#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "miscadmin.h"
#include "storage/procarray.h"
@@ -499,10 +500,21 @@ hash_xlog_move_page_contents(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -627,10 +639,21 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
action = XLogReadBufferForRedo(record, 1, &writebuf);
}
@@ -839,10 +862,21 @@ hash_xlog_delete(XLogReaderState *record)
else
{
/*
- * we don't care for return value as the purpose of reading bucketbuf
- * is to ensure a cleanup lock on primary bucket page.
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so
+ * it has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the
+ * image that repairs it can come later in the WAL.
*/
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ if (HotStandbyActiveInReplay())
+ {
+ /*
+ * we don't care for return value as the purpose of reading
+ * bucketbuf is to ensure a cleanup lock on primary bucket page.
+ */
+ (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ }
action = XLogReadBufferForRedo(record, 1, &deletebuf);
}
diff --git a/src/backend/access/transam/xlogrecovery.c b/src/backend/access/transam/xlogrecovery.c
index 2bc615a691b..7f9ec6d8075 100644
--- a/src/backend/access/transam/xlogrecovery.c
+++ b/src/backend/access/transam/xlogrecovery.c
@@ -441,7 +441,6 @@ static int XLogFileReadAnyTLI(XLogSegNo segno, int emode, XLogSource source);
static bool CheckForStandbyTrigger(void);
static void SetPromoteIsTriggered(void);
-static bool HotStandbyActiveInReplay(void);
static void SetCurrentChunkStartTime(TimestampTz xtime);
static void SetLatestXTime(TimestampTz xtime);
@@ -4528,7 +4527,7 @@ HotStandbyActive(void)
* Like HotStandbyActive(), but to be used only in WAL replay code,
* where we don't need to ask any other process what the state is.
*/
-static bool
+bool
HotStandbyActiveInReplay(void)
{
Assert(AmStartupProcess() || !IsPostmasterEnvironment);
diff --git a/src/include/access/xlogrecovery.h b/src/include/access/xlogrecovery.h
index 7737f9e2cf0..0c25471c2e5 100644
--- a/src/include/access/xlogrecovery.h
+++ b/src/include/access/xlogrecovery.h
@@ -136,6 +136,7 @@ extern void ShutdownWalRecovery(void);
extern void RemovePromoteSignalFiles(void);
extern bool HotStandbyActive(void);
+extern bool HotStandbyActiveInReplay(void);
extern XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI);
extern RecoveryPauseState GetRecoveryPauseState(void);
extern void SetRecoveryPause(bool recoveryPause);
--
2.55.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-17 11:20 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-17 20:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-18 07:13 ` Amit Kapila <amit.kapila16@gmail.com>
2026-11-18 08:33 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-18 11:47 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
0 siblings, 2 replies; 34+ messages in thread
From: Amit Kapila @ 2026-11-18 07:13 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; +Cc: vignesh C <vignesh21@gmail.com>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; Joao Rito <joaovictor.rito@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
On Wed, Nov 18, 2026 at 1:51 AM Greg Burd <greg@burd.me> wrote:
>
> Amit, Vignesh,
>
> Agreed, and thanks Vignesh for splitting it out. v13 is what I had in
> mind: the torn-page read fix on its own, backpatchable, with the
> recovery test and the HEAD-only rework (dropping the pin-only
> registration, removing REGBUF_NO_CHANGE) left for a separate commit on
> master once this is in.
>
Pushed. Next, I suggest we can work on the patch for "dropping the
pin-only registration". Once that is committed, we can move to
removing REGBUF_NO_CHANGE.
--
With Regards,
Amit Kapila.
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-17 11:20 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-17 20:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-18 07:13 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
@ 2026-11-18 08:33 ` vignesh C <vignesh21@gmail.com>
2026-11-18 13:11 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
1 sibling, 1 reply; 34+ messages in thread
From: vignesh C @ 2026-11-18 08:33 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: Greg Burd <greg@burd.me>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; Joao Rito <joaovictor.rito@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
On Wed, 18 Nov 2026 at 12:43, Amit Kapila <amit.kapila16@gmail.com> wrote:
>
> On Wed, Nov 18, 2026 at 1:51 AM Greg Burd <greg@burd.me> wrote:
> >
> > Amit, Vignesh,
> >
> > Agreed, and thanks Vignesh for splitting it out. v13 is what I had in
> > mind: the torn-page read fix on its own, backpatchable, with the
> > recovery test and the HEAD-only rework (dropping the pin-only
> > registration, removing REGBUF_NO_CHANGE) left for a separate commit on
> > master once this is in.
> >
>
> Pushed. Next, I suggest we can work on the patch for "dropping the
> pin-only registration". Once that is committed, we can move to
> removing REGBUF_NO_CHANGE.
Thanks for pushing this patch, here is the rebased patch for the
pin-only registration changes.
Regards,
Vignesh
Attachments: download all (2 files, .tar.gz)
v13-0001-Don-t-register-pin-only-primary-bucket-pages-in-.patch (application/octet-stream, 23.2K) download
From c5324db65d562ed95c0007535c12b19c959d7a93 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v13 1/3] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that no scan on a hot standby is in progress in the bucket, and
none can start, while tuples are removed or moved. That lock was
obtained by registering the page (pin-only) with REGBUF_NO_CHANGE; redo
never reads data from the block, the registration existed only for the
lock. That broke the rule that a registered buffer is one the caller
holds exclusively locked and dirty, and under wal_consistency_checking
it forced a full-page image of a page a concurrent inserter could still
modify, so the record CRC was computed over shifting data.
Stop registering the primary bucket page when the record does not change
it. When the page is not one of the pages the record changes, the
operation holds only a pin on it, so the record carries the page's block
number in its main data and replay reads that block and takes a cleanup
lock on it directly, at the same point and in the same order as before.
The block number is appended only in that case, so the records are no
larger than before in the common case where the primary bucket page is
registered.
After this change hash registers only buffers it holds exclusively
locked and dirty, and there are no REGBUF_NO_CHANGE users left.
The three record formats change, so bump XLOG_PAGE_MAGIC; master only.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Discussion: https://postgr.es/m/auNs8b_vS2OPdTL8@floki
---
src/backend/access/hash/README | 9 ++
src/backend/access/hash/hash.c | 18 ++--
src/backend/access/hash/hash_xlog.c | 134 ++++++++++++++--------------
src/backend/access/hash/hashovfl.c | 99 +++++++++-----------
src/include/access/hash_xlog.h | 37 +++++---
src/include/access/xlog_internal.h | 2 +-
6 files changed, 154 insertions(+), 145 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record then carries its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..9a919654ce5 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -909,19 +909,17 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * Replay must take a cleanup lock on the primary bucket page
+ * to serialize with scans on a hot standby. If buf is an
+ * overflow page, the unchanged primary page is held only by a
+ * pin, so append its block number instead of registering it.
+ * Otherwise block 0 identifies the primary page.
*/
if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
- XLogRegisterBufData(1, deletable,
+ XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_DELETE);
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 46047c6ea27..37ea8099f23 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -470,6 +470,42 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on an unregistered primary bucket page, whose block
+ * number is stored in the record's main data. This serializes replay against
+ * scans on a hot standby. block_id must identify a registered block of the
+ * same index.
+ */
+static Buffer
+hash_xlog_lock_primary_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ BlockNumber bucket_blkno;
+ Buffer buf;
+
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
+ /*
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so it
+ * has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the image
+ * that repairs it can come later in the WAL.
+ */
+ if (!HotStandbyActiveInReplay())
+ return InvalidBuffer;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -491,27 +527,12 @@ hash_xlog_move_page_contents(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * The cleanup lock is needed only when hot standby is active, because
- * scans cannot run before that. Skipping the read also avoids a torn
- * copy of the primary page. This record does not modify that page, so
- * it has no full-page image of it. In crash recovery, or on a standby
- * started from a base backup, the page on disk can be torn and the
- * image that repairs it can come later in the WAL.
- */
- if (HotStandbyActiveInReplay())
- {
- /*
- * we don't care for return value as the purpose of reading
- * bucketbuf is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
- }
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashMovePageContents);
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
}
/* replay the record for adding entries in overflow buffer */
@@ -523,7 +544,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
Size datalen;
uint16 ninserted = 0;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -562,13 +583,13 @@ hash_xlog_move_page_contents(XLogReaderState *record)
}
/* replay the record for deleting entries from overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &deletebuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &deletebuf) == BLK_NEEDS_REDO)
{
Page page;
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 2, &len);
+ ptr = XLogRecGetBlockData(record, 1, &len);
page = BufferGetPage(deletebuf);
@@ -629,28 +650,26 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
- else
{
/*
- * The cleanup lock is needed only when hot standby is active, because
- * scans cannot run before that. Skipping the read also avoids a torn
- * copy of the primary page. This record does not modify that page, so
- * it has no full-page image of it. In crash recovery, or on a standby
- * started from a base backup, the page on disk can be torn and the
- * image that repairs it can come later in the WAL.
+ * If the primary bucket page is modified, it is registered as block
+ * 0 and read for redo. Otherwise, acquire its cleanup lock
+ * separately.
*/
- if (HotStandbyActiveInReplay())
+ if (XLogRecHasBlockRef(record, 0))
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
+ else
{
- /*
- * we don't care for return value as the purpose of reading
- * bucketbuf is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
+ action = BLK_NOTFOUND;
}
+ }
+ else
+ {
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
else
action = BLK_NOTFOUND;
}
@@ -665,7 +684,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint16 ninserted = 0;
bool mod_wbuf = false;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -731,7 +750,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
}
/* replay the record for initializing overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &ovflbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &ovflbuf) == BLK_NEEDS_REDO)
{
Page ovflpage;
HashPageOpaque ovflopaque;
@@ -756,7 +775,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/* replay the record for page previous to the freed overflow page */
if (!xldata->is_prev_bucket_same_wrt &&
- XLogReadBufferForRedo(record, 3, &prevbuf) == BLK_NEEDS_REDO)
+ XLogReadBufferForRedo(record, 2, &prevbuf) == BLK_NEEDS_REDO)
{
Page prevpage = BufferGetPage(prevbuf);
HashPageOpaque prevopaque = HashPageGetOpaque(prevpage);
@@ -770,11 +789,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(prevbuf);
/* replay the record for page next to the freed overflow page */
- if (XLogRecHasBlockRef(record, 4))
+ if (XLogRecHasBlockRef(record, 3))
{
Buffer nextbuf;
- if (XLogReadBufferForRedo(record, 4, &nextbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 3, &nextbuf) == BLK_NEEDS_REDO)
{
Page nextpage = BufferGetPage(nextbuf);
HashPageOpaque nextopaque = HashPageGetOpaque(nextpage);
@@ -801,7 +820,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* index updates can be happening concurrently.
*/
/* replay the record for bitmap page */
- if (XLogReadBufferForRedo(record, 5, &mapbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 4, &mapbuf) == BLK_NEEDS_REDO)
{
Page mappage = BufferGetPage(mapbuf);
uint32 *freep = NULL;
@@ -811,7 +830,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
freep = HashPageGetBitmap(mappage);
- data = XLogRecGetBlockData(record, 5, &datalen);
+ data = XLogRecGetBlockData(record, 4, &datalen);
bitmap_page_bit = (uint32 *) data;
CLRBIT(freep, *bitmap_page_bit);
@@ -823,11 +842,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(mapbuf);
/* replay the record for meta page */
- if (XLogRecHasBlockRef(record, 6))
+ if (XLogRecHasBlockRef(record, 5))
{
Buffer metabuf;
- if (XLogReadBufferForRedo(record, 6, &metabuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 5, &metabuf) == BLK_NEEDS_REDO)
{
HashMetaPage metap;
Page page;
@@ -835,7 +854,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint32 *firstfree_ovflpage;
Size datalen;
- data = XLogRecGetBlockData(record, 6, &datalen);
+ data = XLogRecGetBlockData(record, 5, &datalen);
firstfree_ovflpage = (uint32 *) data;
page = BufferGetPage(metabuf);
@@ -871,27 +890,12 @@ hash_xlog_delete(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_primary_bucket_page)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * The cleanup lock is needed only when hot standby is active, because
- * scans cannot run before that. Skipping the read also avoids a torn
- * copy of the primary page. This record does not modify that page, so
- * it has no full-page image of it. In crash recovery, or on a standby
- * started from a base backup, the page on disk can be torn and the
- * image that repairs it can come later in the WAL.
- */
- if (HotStandbyActiveInReplay())
- {
- /*
- * we don't care for return value as the purpose of reading
- * bucketbuf is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
- }
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashDelete);
- action = XLogReadBufferForRedo(record, 1, &deletebuf);
+ action = XLogReadBufferForRedo(record, 0, &deletebuf);
}
/* replay the record for deleting entries in bucket page */
@@ -900,7 +904,7 @@ hash_xlog_delete(XLogReaderState *record)
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 1, &len);
+ ptr = XLogRecGetBlockData(record, 0, &len);
page = BufferGetPage(deletebuf);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..35f214767bd 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,6 +660,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
@@ -667,45 +672,26 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Replay needs the primary bucket block number to acquire a cleanup
+ * lock. Register it as block 0 when it is modified; otherwise append
+ * its block number to the record.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- if (nitups > 0)
- {
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
+ if (mod_wbuf)
{
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(0, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
+ }
}
- XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(1, ovflbuf, REGBUF_STANDARD);
/*
* If prevpage and the writepage (block in which we are moving tuples
@@ -714,18 +700,18 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* writepage.
*/
if (BufferIsValid(prevbuf) && !is_prev_bucket_same_wrt)
- XLogRegisterBuffer(3, prevbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(2, prevbuf, REGBUF_STANDARD);
if (BufferIsValid(nextbuf))
- XLogRegisterBuffer(4, nextbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(3, nextbuf, REGBUF_STANDARD);
- XLogRegisterBuffer(5, mapbuf, REGBUF_STANDARD);
- XLogRegisterBufData(5, &bitmapbit, sizeof(uint32));
+ XLogRegisterBuffer(4, mapbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(4, &bitmapbit, sizeof(uint32));
if (update_metap)
{
- XLogRegisterBuffer(6, metabuf, REGBUF_STANDARD);
- XLogRegisterBufData(6, &metap->hashm_firstfree, sizeof(uint32));
+ XLogRegisterBuffer(5, metabuf, REGBUF_STANDARD);
+ XLogRegisterBufData(5, &metap->hashm_firstfree, sizeof(uint32));
}
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SQUEEZE_PAGE);
@@ -966,10 +952,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -998,25 +986,22 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, itup_offsets,
nitups * sizeof(OffsetNumber));
for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
- XLogRegisterBuffer(2, rbuf, REGBUF_STANDARD);
- XLogRegisterBufData(2, deletable,
+ XLogRegisterBuffer(1, rbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_MOVE_PAGE_CONTENTS);
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..0bb0d0590f5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,9 +129,13 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing moved tuples
- * Backup Blk 2: page from which tuples will be removed
+ * Backup Blk 0: page containing moved tuples
+ * Backup Blk 1: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
@@ -149,13 +153,18 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
- * Backup Blk 2: freed overflow page
- * Backup Blk 3: page previous to the freed overflow page
- * Backup Blk 4: page next to the freed overflow page
- * Backup Blk 5: bitmap page containing info of freed overflow page
- * Backup Blk 6: meta page
+ * Backup Blk 0: page containing tuples moved from freed overflow page, if
+ * it is modified
+ * Backup Blk 1: freed overflow page
+ * Backup Blk 2: page previous to the freed overflow page
+ * Backup Blk 3: page next to the freed overflow page
+ * Backup Blk 4: bitmap page containing info of freed overflow page
+ * Backup Blk 5: meta page
+ *
+ * The primary bucket page is registered only as block 0, when it is the
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
@@ -179,8 +188,12 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page from which tuples are deleted
+ * Backup Blk 0: page from which tuples are deleted
+ *
+ * If block 0 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
--
2.55.0
v13-0002-Add-a-recovery-test-for-the-hash-WAL-pin-only-bu.patch (application/octet-stream, 11.7K) download
From 650ac72e00f69bd867f8c261abd15ece26e2a917 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v13 2/3] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/061_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 ++
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_vacuum_insert_crc.pl | 191 ++++++++++++++++++
3 files changed, 214 insertions(+)
create mode 100644 src/test/recovery/t/061_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..5051031df56 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_vacuum_insert_crc.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_vacuum_insert_crc.pl b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..89f7611af12
--- /dev/null
+++ b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
@@ -0,0 +1,191 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# The first and the last WAL segment of the range. With only --path, pg_waldump
+# takes the WAL segment size from the first file readdir() returns, which can be
+# a zero-filled, unused segment, and then fails with "invalid WAL segment size".
+# Naming the segments makes it read the size from the first of them.
+my $start_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$start_lsn')");
+my $end_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.55.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-17 11:20 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-17 20:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-18 07:13 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-18 08:33 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
@ 2026-11-18 13:11 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-18 18:24 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
0 siblings, 1 reply; 34+ messages in thread
From: Hayato Kuroda (Fujitsu) @ 2026-11-18 13:11 UTC (permalink / raw)
To: vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; +Cc: Greg Burd <greg@burd.me>; Joao Rito <joaovictor.rito@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>
Hi,
Thanks for updating the patch! I checked 0001 again and here is my comment.
```
if (xldata->is_prim_bucket_same_wrt)
{
/*
* If the primary bucket page is modified, it is registered as block
* 0 and read for redo. Otherwise, acquire its cleanup lock
* separately.
*/
if (XLogRecHasBlockRef(record, 0))
action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
action = BLK_NOTFOUND;
}
}
else
{
bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
action = XLogReadBufferForRedo(record, 0, &writebuf);
else
action = BLK_NOTFOUND;
}
```
While reading the code again, I came up with another idea to clean up the code:
how about making the code similar with the WAL generation side? Something like
attached. Or is it matter of taste?
For now I cannot find other comments.
Best regards,
Hayato Kuroda
FUJITSU LIMITED
Attachments:
nocfbot-0001-simplify-hash_xlog_squeeze_page.patch (application/octet-stream, 2.4K) download
From 2371aaa1483051fc8b81256a271e45ac4c5c472e Mon Sep 17 00:00:00 2001
From: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Date: Wed, 18 Nov 2026 22:02:54 +0900
Subject: [PATCH vnocfbot] simplify hash_xlog_squeeze_page
---
src/backend/access/hash/hash_xlog.c | 36 +++++++++++------------------
1 file changed, 14 insertions(+), 22 deletions(-)
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 37ea8099f23..f4816486618 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -641,6 +641,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
Buffer prevbuf = InvalidBuffer;
Buffer mapbuf;
XLogRedoAction action;
+ bool writebuf_registered;
/*
* Ensure we have a cleanup lock on primary bucket page before we start
@@ -648,31 +649,22 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* scan can start nor a scan can be already-in-progress during the replay
* of this operation. If we allow scans during this operation, then they
* can miss some records or show the same record multiple times.
+ *
+ * A modified write page is registered as block 0. If it is also the
+ * primary bucket page, its cleanup lock protects scans; otherwise, lock
+ * the primary bucket page separately.
*/
- if (xldata->is_prim_bucket_same_wrt)
- {
- /*
- * If the primary bucket page is modified, it is registered as block
- * 0 and read for redo. Otherwise, acquire its cleanup lock
- * separately.
- */
- if (XLogRecHasBlockRef(record, 0))
- action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
- else
- {
- bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
- action = BLK_NOTFOUND;
- }
- }
- else
- {
+ writebuf_registered = XLogRecHasBlockRef(record, 0);
+
+ if (!(xldata->is_prim_bucket_same_wrt && writebuf_registered))
bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
- if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 0, &writebuf);
- else
- action = BLK_NOTFOUND;
- }
+ if (writebuf_registered)
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL,
+ xldata->is_prim_bucket_same_wrt,
+ &writebuf);
+ else
+ action = BLK_NOTFOUND;
/* replay the record for adding entries in overflow buffer */
if (action == BLK_NEEDS_REDO)
--
2.52.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-17 11:20 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-17 20:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-18 07:13 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-18 08:33 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-18 13:11 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
@ 2026-11-18 18:24 ` Greg Burd <greg@burd.me>
2026-11-20 15:01 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
0 siblings, 1 reply; 34+ messages in thread
From: Greg Burd @ 2026-11-18 18:24 UTC (permalink / raw)
To: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; +Cc: pgsql-hackers@lists.postgresql.org, 'vignesh C' <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Joao Rito <joaovictor.rito@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>
On Wednesday, November 18th, 2026 at 8:11 AM, Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com> wrote:
> Hi,
Hi Hayato-san,
> Thanks for updating the patch! I checked 0001 again and here is my comment.
> While reading the code again, I came up with another idea to clean up
> the code: how about making the code similar with the WAL generation
> side? Something like attached. Or is it matter of taste?
It reads better, thanks. XLogRecHasBlockRef(record, 0) on the redo side
is exactly mod_wbuf on the generation side (nitups > 0 ||
is_prev_bucket_same_wrt), which is when _hash_freeovflpage() registers
block 0, so folding the two branches into one writebuf_registered flag
is equivalent and mirrors the writer. I took it in v15.
The one thing I kept from the original is reading the primary bucket
page's cleanup lock before the write buffer in the non-same-wrt case,
which your version preserves: hash_xlog_lock_primary_bucket() still runs
first when the write page is not the primary bucket page.
v15 attached, rebased onto b8cbc63dcc7.
0001: fold your simplification into hash_xlog_squeeze_page().
0001 passes the recovery suite under the CI UBSan flags and 061 passes,
as before. I think 0001 and 0002 are ready; does one of you want to
take them, or is there more you want to see first?
best.
-greg
Attachments: download all (2 files, .tar.gz)
v15-0001-Don-t-register-pin-only-primary-bucket-pages-in-.patch (text/x-patch, 24.6K) download
From 6581bb9556eab4393664e7dc3af2fd16e5e78d74 Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v15 1/2] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that no scan on a hot standby is in progress in the bucket, and
none can start, while tuples are removed or moved. That lock was
obtained by registering the page (pin-only) with REGBUF_NO_CHANGE; redo
never reads data from the block, the registration existed only for the
lock. That broke the rule that a registered buffer is one the caller
holds exclusively locked and dirty, and under wal_consistency_checking
it forced a full-page image of a page a concurrent inserter could still
modify, so the record CRC was computed over shifting data.
Stop registering the primary bucket page when the record does not change
it. When the page is not one of the pages the record changes, the
operation holds only a pin on it, so the record carries the page's block
number in its main data and replay reads that block and takes a cleanup
lock on it directly, at the same point and in the same order as before.
The block number is appended only in that case, so the records are no
larger than before in the common case where the primary bucket page is
registered. Replay takes the cleanup lock in a new helper,
hash_xlog_lock_primary_bucket(), shared by the three redo routines.
After this change hash no longer uses REGBUF_NO_CHANGE; a follow-up
removes the flag itself.
The three record formats change, so bump XLOG_PAGE_MAGIC; master only.
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Discussion: https://postgr.es/m/auNs8b_vS2OPdTL8@floki
---
src/backend/access/hash/README | 9 ++
src/backend/access/hash/hash.c | 18 ++--
src/backend/access/hash/hash_xlog.c | 146 ++++++++++++++--------------
src/backend/access/hash/hashovfl.c | 99 ++++++++-----------
src/include/access/hash_xlog.h | 37 ++++---
src/include/access/xlog_internal.h | 2 +-
6 files changed, 156 insertions(+), 155 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record then carries its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..9a919654ce5 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -909,19 +909,17 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * Replay must take a cleanup lock on the primary bucket page
+ * to serialize with scans on a hot standby. If buf is an
+ * overflow page, the unchanged primary page is held only by a
+ * pin, so append its block number instead of registering it.
+ * Otherwise block 0 identifies the primary page.
*/
if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
- XLogRegisterBufData(1, deletable,
+ XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_DELETE);
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 46047c6ea27..f4816486618 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -470,6 +470,42 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on an unregistered primary bucket page, whose block
+ * number is stored in the record's main data. This serializes replay against
+ * scans on a hot standby. block_id must identify a registered block of the
+ * same index.
+ */
+static Buffer
+hash_xlog_lock_primary_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ BlockNumber bucket_blkno;
+ Buffer buf;
+
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
+ /*
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so it
+ * has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the image
+ * that repairs it can come later in the WAL.
+ */
+ if (!HotStandbyActiveInReplay())
+ return InvalidBuffer;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -491,27 +527,12 @@ hash_xlog_move_page_contents(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * The cleanup lock is needed only when hot standby is active, because
- * scans cannot run before that. Skipping the read also avoids a torn
- * copy of the primary page. This record does not modify that page, so
- * it has no full-page image of it. In crash recovery, or on a standby
- * started from a base backup, the page on disk can be torn and the
- * image that repairs it can come later in the WAL.
- */
- if (HotStandbyActiveInReplay())
- {
- /*
- * we don't care for return value as the purpose of reading
- * bucketbuf is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
- }
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashMovePageContents);
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
}
/* replay the record for adding entries in overflow buffer */
@@ -523,7 +544,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
Size datalen;
uint16 ninserted = 0;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -562,13 +583,13 @@ hash_xlog_move_page_contents(XLogReaderState *record)
}
/* replay the record for deleting entries from overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &deletebuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &deletebuf) == BLK_NEEDS_REDO)
{
Page page;
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 2, &len);
+ ptr = XLogRecGetBlockData(record, 1, &len);
page = BufferGetPage(deletebuf);
@@ -620,6 +641,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
Buffer prevbuf = InvalidBuffer;
Buffer mapbuf;
XLogRedoAction action;
+ bool writebuf_registered;
/*
* Ensure we have a cleanup lock on primary bucket page before we start
@@ -627,33 +649,22 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* scan can start nor a scan can be already-in-progress during the replay
* of this operation. If we allow scans during this operation, then they
* can miss some records or show the same record multiple times.
+ *
+ * A modified write page is registered as block 0. If it is also the
+ * primary bucket page, its cleanup lock protects scans; otherwise, lock
+ * the primary bucket page separately.
*/
- if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
- else
- {
- /*
- * The cleanup lock is needed only when hot standby is active, because
- * scans cannot run before that. Skipping the read also avoids a torn
- * copy of the primary page. This record does not modify that page, so
- * it has no full-page image of it. In crash recovery, or on a standby
- * started from a base backup, the page on disk can be torn and the
- * image that repairs it can come later in the WAL.
- */
- if (HotStandbyActiveInReplay())
- {
- /*
- * we don't care for return value as the purpose of reading
- * bucketbuf is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
- }
+ writebuf_registered = XLogRecHasBlockRef(record, 0);
- if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 1, &writebuf);
- else
- action = BLK_NOTFOUND;
- }
+ if (!(xldata->is_prim_bucket_same_wrt && writebuf_registered))
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
+
+ if (writebuf_registered)
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL,
+ xldata->is_prim_bucket_same_wrt,
+ &writebuf);
+ else
+ action = BLK_NOTFOUND;
/* replay the record for adding entries in overflow buffer */
if (action == BLK_NEEDS_REDO)
@@ -665,7 +676,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint16 ninserted = 0;
bool mod_wbuf = false;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -731,7 +742,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
}
/* replay the record for initializing overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &ovflbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &ovflbuf) == BLK_NEEDS_REDO)
{
Page ovflpage;
HashPageOpaque ovflopaque;
@@ -756,7 +767,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/* replay the record for page previous to the freed overflow page */
if (!xldata->is_prev_bucket_same_wrt &&
- XLogReadBufferForRedo(record, 3, &prevbuf) == BLK_NEEDS_REDO)
+ XLogReadBufferForRedo(record, 2, &prevbuf) == BLK_NEEDS_REDO)
{
Page prevpage = BufferGetPage(prevbuf);
HashPageOpaque prevopaque = HashPageGetOpaque(prevpage);
@@ -770,11 +781,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(prevbuf);
/* replay the record for page next to the freed overflow page */
- if (XLogRecHasBlockRef(record, 4))
+ if (XLogRecHasBlockRef(record, 3))
{
Buffer nextbuf;
- if (XLogReadBufferForRedo(record, 4, &nextbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 3, &nextbuf) == BLK_NEEDS_REDO)
{
Page nextpage = BufferGetPage(nextbuf);
HashPageOpaque nextopaque = HashPageGetOpaque(nextpage);
@@ -801,7 +812,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* index updates can be happening concurrently.
*/
/* replay the record for bitmap page */
- if (XLogReadBufferForRedo(record, 5, &mapbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 4, &mapbuf) == BLK_NEEDS_REDO)
{
Page mappage = BufferGetPage(mapbuf);
uint32 *freep = NULL;
@@ -811,7 +822,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
freep = HashPageGetBitmap(mappage);
- data = XLogRecGetBlockData(record, 5, &datalen);
+ data = XLogRecGetBlockData(record, 4, &datalen);
bitmap_page_bit = (uint32 *) data;
CLRBIT(freep, *bitmap_page_bit);
@@ -823,11 +834,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(mapbuf);
/* replay the record for meta page */
- if (XLogRecHasBlockRef(record, 6))
+ if (XLogRecHasBlockRef(record, 5))
{
Buffer metabuf;
- if (XLogReadBufferForRedo(record, 6, &metabuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 5, &metabuf) == BLK_NEEDS_REDO)
{
HashMetaPage metap;
Page page;
@@ -835,7 +846,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint32 *firstfree_ovflpage;
Size datalen;
- data = XLogRecGetBlockData(record, 6, &datalen);
+ data = XLogRecGetBlockData(record, 5, &datalen);
firstfree_ovflpage = (uint32 *) data;
page = BufferGetPage(metabuf);
@@ -871,27 +882,12 @@ hash_xlog_delete(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_primary_bucket_page)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * The cleanup lock is needed only when hot standby is active, because
- * scans cannot run before that. Skipping the read also avoids a torn
- * copy of the primary page. This record does not modify that page, so
- * it has no full-page image of it. In crash recovery, or on a standby
- * started from a base backup, the page on disk can be torn and the
- * image that repairs it can come later in the WAL.
- */
- if (HotStandbyActiveInReplay())
- {
- /*
- * we don't care for return value as the purpose of reading
- * bucketbuf is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
- }
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashDelete);
- action = XLogReadBufferForRedo(record, 1, &deletebuf);
+ action = XLogReadBufferForRedo(record, 0, &deletebuf);
}
/* replay the record for deleting entries in bucket page */
@@ -900,7 +896,7 @@ hash_xlog_delete(XLogReaderState *record)
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 1, &len);
+ ptr = XLogRecGetBlockData(record, 0, &len);
page = BufferGetPage(deletebuf);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..35f214767bd 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,6 +660,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
@@ -667,45 +672,26 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Replay needs the primary bucket block number to acquire a cleanup
+ * lock. Register it as block 0 when it is modified; otherwise append
+ * its block number to the record.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- if (nitups > 0)
- {
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
+ if (mod_wbuf)
{
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(0, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
+ }
}
- XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(1, ovflbuf, REGBUF_STANDARD);
/*
* If prevpage and the writepage (block in which we are moving tuples
@@ -714,18 +700,18 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* writepage.
*/
if (BufferIsValid(prevbuf) && !is_prev_bucket_same_wrt)
- XLogRegisterBuffer(3, prevbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(2, prevbuf, REGBUF_STANDARD);
if (BufferIsValid(nextbuf))
- XLogRegisterBuffer(4, nextbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(3, nextbuf, REGBUF_STANDARD);
- XLogRegisterBuffer(5, mapbuf, REGBUF_STANDARD);
- XLogRegisterBufData(5, &bitmapbit, sizeof(uint32));
+ XLogRegisterBuffer(4, mapbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(4, &bitmapbit, sizeof(uint32));
if (update_metap)
{
- XLogRegisterBuffer(6, metabuf, REGBUF_STANDARD);
- XLogRegisterBufData(6, &metap->hashm_firstfree, sizeof(uint32));
+ XLogRegisterBuffer(5, metabuf, REGBUF_STANDARD);
+ XLogRegisterBufData(5, &metap->hashm_firstfree, sizeof(uint32));
}
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SQUEEZE_PAGE);
@@ -966,10 +952,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -998,25 +986,22 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, itup_offsets,
nitups * sizeof(OffsetNumber));
for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
- XLogRegisterBuffer(2, rbuf, REGBUF_STANDARD);
- XLogRegisterBufData(2, deletable,
+ XLogRegisterBuffer(1, rbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_MOVE_PAGE_CONTENTS);
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..0bb0d0590f5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,9 +129,13 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing moved tuples
- * Backup Blk 2: page from which tuples will be removed
+ * Backup Blk 0: page containing moved tuples
+ * Backup Blk 1: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
@@ -149,13 +153,18 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
- * Backup Blk 2: freed overflow page
- * Backup Blk 3: page previous to the freed overflow page
- * Backup Blk 4: page next to the freed overflow page
- * Backup Blk 5: bitmap page containing info of freed overflow page
- * Backup Blk 6: meta page
+ * Backup Blk 0: page containing tuples moved from freed overflow page, if
+ * it is modified
+ * Backup Blk 1: freed overflow page
+ * Backup Blk 2: page previous to the freed overflow page
+ * Backup Blk 3: page next to the freed overflow page
+ * Backup Blk 4: bitmap page containing info of freed overflow page
+ * Backup Blk 5: meta page
+ *
+ * The primary bucket page is registered only as block 0, when it is the
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
@@ -179,8 +188,12 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page from which tuples are deleted
+ * Backup Blk 0: page from which tuples are deleted
+ *
+ * If block 0 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
base-commit: b8cbc63dcc77cd2b9cbee2bc7ca64e471a2118ee
--
2.54.0
v15-0002-Add-a-recovery-test-for-the-hash-WAL-pin-only-bu.patch (text/x-patch, 12.1K) download
From 959edebc3ac8002e1312098c76572f39377e91cf Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v15 2/2] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/061_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Joao Rito <joaovictor.rito@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 ++
src/test/recovery/meson.build | 1 +
.../recovery/t/061_hash_vacuum_insert_crc.pl | 191 ++++++++++++++++++
3 files changed, 214 insertions(+)
create mode 100644 src/test/recovery/t/061_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 341deb7b80d..cd3359434e1 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -991,6 +992,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index b6ac9dd07a7..5051031df56 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -69,6 +69,7 @@ tests += {
't/058_shutdown_crash_restart.pl',
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
+ 't/061_hash_vacuum_insert_crc.pl',
],
},
}
diff --git a/src/test/recovery/t/061_hash_vacuum_insert_crc.pl b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..89f7611af12
--- /dev/null
+++ b/src/test/recovery/t/061_hash_vacuum_insert_crc.pl
@@ -0,0 +1,191 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# The first and the last WAL segment of the range. With only --path, pg_waldump
+# takes the WAL segment size from the first file readdir() returns, which can be
+# a zero-filled, unused segment, and then fails with "invalid WAL segment size".
+# Naming the segments makes it read the size from the first of them.
+my $start_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$start_lsn')");
+my $end_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.54.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-17 11:20 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-17 20:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-18 07:13 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-18 08:33 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-18 13:11 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-18 18:24 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-20 15:01 ` Greg Burd <greg@burd.me>
2026-11-21 18:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
0 siblings, 1 reply; 34+ messages in thread
From: Greg Burd @ 2026-11-20 15:01 UTC (permalink / raw)
To: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; +Cc: pgsql-hackers@lists.postgresql.org, 'vignesh C' <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Joao Rito <joaovictor.rito@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>
Hi all,
v16 attached, rebased onto 70cc154f62. No code change from v15.
Upstream added src/test/recovery/t/061_recovery_target_prefetch.pl,
which took the 061 slot the test used, so v15 no longer applies and
cfbot would show it as rebase-needed. v16 renumbers the test to 062
(062_hash_vacuum_insert_crc.pl) and is otherwise identical to v15.
0002: rename 061_hash_vacuum_insert_crc.pl to 062, since upstream
now uses 061.
Still looking for a committer to take 0001 and 0002.
-greg
Attachments: download all (2 files, .tar.gz)
v16-0001-Don-t-register-pin-only-primary-bucket-pages-in-.patch (text/x-patch, 24.6K) download
From 1844a928bc85b8ae7bb99e6fc6e64a49bf6af43d Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Thu, 29 Oct 2026 10:30:14 -0400
Subject: [PATCH v16 1/2] Don't register pin-only primary bucket pages in hash
WAL records
Replay of XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE must take a cleanup lock on the primary bucket
page so that no scan on a hot standby is in progress in the bucket, and
none can start, while tuples are removed or moved. That lock was
obtained by registering the page (pin-only) with REGBUF_NO_CHANGE; redo
never reads data from the block, the registration existed only for the
lock. That broke the rule that a registered buffer is one the caller
holds exclusively locked and dirty, and under wal_consistency_checking
it forced a full-page image of a page a concurrent inserter could still
modify, so the record CRC was computed over shifting data.
Stop registering the primary bucket page when the record does not change
it. When the page is not one of the pages the record changes, the
operation holds only a pin on it, so the record carries the page's block
number in its main data and replay reads that block and takes a cleanup
lock on it directly, at the same point and in the same order as before.
The block number is appended only in that case, so the records are no
larger than before in the common case where the primary bucket page is
registered. Replay takes the cleanup lock in a new helper,
hash_xlog_lock_primary_bucket(), shared by the three redo routines.
After this change hash no longer uses REGBUF_NO_CHANGE; a follow-up
removes the flag itself.
The three record formats change, so bump XLOG_PAGE_MAGIC; master only.
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Suggested-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Hayato Kuroda <kuroda.hayato@fujitsu.com>
Discussion: https://postgr.es/m/auNs8b_vS2OPdTL8@floki
---
src/backend/access/hash/README | 9 ++
src/backend/access/hash/hash.c | 18 ++--
src/backend/access/hash/hash_xlog.c | 146 ++++++++++++++--------------
src/backend/access/hash/hashovfl.c | 99 ++++++++-----------
src/include/access/hash_xlog.h | 37 ++++---
src/include/access/xlog_internal.h | 2 +-
6 files changed, 156 insertions(+), 155 deletions(-)
diff --git a/src/backend/access/hash/README b/src/backend/access/hash/README
index fc9031117c9..7774e1d2fe0 100644
--- a/src/backend/access/hash/README
+++ b/src/backend/access/hash/README
@@ -641,6 +641,15 @@ entire bucket. After recovery, the operations will work correctly, but
the index will remain bloated and this can impact performance of read and
insert operations until the next vacuum squeeze the bucket completely.
+Replay of the delete, move-page-contents and squeeze-page records takes a
+cleanup lock on the primary bucket page before touching any other page, so
+that no scan on a hot standby is in progress in the bucket or can start in
+it while tuples are removed or moved; such a scan could otherwise miss
+tuples or return them twice. When the primary bucket page is not one of
+the pages the record changes, the operation holds only a pin on it, so it
+is not registered in the record. The record then carries its block number
+instead, and replay locks that block directly.
+
Other Notes
-----------
diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c
index 63846c10840..9a919654ce5 100644
--- a/src/backend/access/hash/hash.c
+++ b/src/backend/access/hash/hash.c
@@ -909,19 +909,17 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf,
XLogRegisterData(&xlrec, SizeOfHashDelete);
/*
- * bucket buffer was not changed, but still needs to be
- * registered to ensure that we can acquire a cleanup lock on
- * it during replay.
+ * Replay must take a cleanup lock on the primary bucket page
+ * to serialize with scans on a hot standby. If buf is an
+ * overflow page, the unchanged primary page is held only by a
+ * pin, so append its block number instead of registering it.
+ * Otherwise block 0 identifies the primary page.
*/
if (!xlrec.is_primary_bucket_page)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, buf, REGBUF_STANDARD);
- XLogRegisterBufData(1, deletable,
+ XLogRegisterBuffer(0, buf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_DELETE);
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index 46047c6ea27..f4816486618 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -470,6 +470,42 @@ hash_xlog_split_complete(XLogReaderState *record)
UnlockReleaseBuffer(newbuf);
}
+/*
+ * Take a cleanup lock on an unregistered primary bucket page, whose block
+ * number is stored in the record's main data. This serializes replay against
+ * scans on a hot standby. block_id must identify a registered block of the
+ * same index.
+ */
+static Buffer
+hash_xlog_lock_primary_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
+{
+ RelFileLocator rlocator;
+ ForkNumber forknum;
+ BlockNumber bucket_blkno;
+ Buffer buf;
+
+ Assert(XLogRecGetDataLen(record) == rec_size + sizeof(BlockNumber));
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size, sizeof(BlockNumber));
+
+ /*
+ * The cleanup lock is needed only when hot standby is active, because
+ * scans cannot run before that. Skipping the read also avoids a torn
+ * copy of the primary page. This record does not modify that page, so it
+ * has no full-page image of it. In crash recovery, or on a standby
+ * started from a base backup, the page on disk can be torn and the image
+ * that repairs it can come later in the WAL.
+ */
+ if (!HotStandbyActiveInReplay())
+ return InvalidBuffer;
+
+ XLogRecGetBlockTag(record, block_id, &rlocator, &forknum, NULL);
+ buf = XLogReadBufferExtended(rlocator, forknum, bucket_blkno,
+ RBM_NORMAL, InvalidBuffer);
+ if (BufferIsValid(buf))
+ LockBufferForCleanup(buf);
+ return buf;
+}
+
/*
* replay move of page contents for squeeze operation of hash index
*/
@@ -491,27 +527,12 @@ hash_xlog_move_page_contents(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &writebuf);
else
{
- /*
- * The cleanup lock is needed only when hot standby is active, because
- * scans cannot run before that. Skipping the read also avoids a torn
- * copy of the primary page. This record does not modify that page, so
- * it has no full-page image of it. In crash recovery, or on a standby
- * started from a base backup, the page on disk can be torn and the
- * image that repairs it can come later in the WAL.
- */
- if (HotStandbyActiveInReplay())
- {
- /*
- * we don't care for return value as the purpose of reading
- * bucketbuf is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
- }
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashMovePageContents);
- action = XLogReadBufferForRedo(record, 1, &writebuf);
+ action = XLogReadBufferForRedo(record, 0, &writebuf);
}
/* replay the record for adding entries in overflow buffer */
@@ -523,7 +544,7 @@ hash_xlog_move_page_contents(XLogReaderState *record)
Size datalen;
uint16 ninserted = 0;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -562,13 +583,13 @@ hash_xlog_move_page_contents(XLogReaderState *record)
}
/* replay the record for deleting entries from overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &deletebuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &deletebuf) == BLK_NEEDS_REDO)
{
Page page;
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 2, &len);
+ ptr = XLogRecGetBlockData(record, 1, &len);
page = BufferGetPage(deletebuf);
@@ -620,6 +641,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
Buffer prevbuf = InvalidBuffer;
Buffer mapbuf;
XLogRedoAction action;
+ bool writebuf_registered;
/*
* Ensure we have a cleanup lock on primary bucket page before we start
@@ -627,33 +649,22 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* scan can start nor a scan can be already-in-progress during the replay
* of this operation. If we allow scans during this operation, then they
* can miss some records or show the same record multiple times.
+ *
+ * A modified write page is registered as block 0. If it is also the
+ * primary bucket page, its cleanup lock protects scans; otherwise, lock
+ * the primary bucket page separately.
*/
- if (xldata->is_prim_bucket_same_wrt)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &writebuf);
- else
- {
- /*
- * The cleanup lock is needed only when hot standby is active, because
- * scans cannot run before that. Skipping the read also avoids a torn
- * copy of the primary page. This record does not modify that page, so
- * it has no full-page image of it. In crash recovery, or on a standby
- * started from a base backup, the page on disk can be torn and the
- * image that repairs it can come later in the WAL.
- */
- if (HotStandbyActiveInReplay())
- {
- /*
- * we don't care for return value as the purpose of reading
- * bucketbuf is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
- }
+ writebuf_registered = XLogRecHasBlockRef(record, 0);
- if (xldata->ntups > 0 || xldata->is_prev_bucket_same_wrt)
- action = XLogReadBufferForRedo(record, 1, &writebuf);
- else
- action = BLK_NOTFOUND;
- }
+ if (!(xldata->is_prim_bucket_same_wrt && writebuf_registered))
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 1, SizeOfHashSqueezePage);
+
+ if (writebuf_registered)
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL,
+ xldata->is_prim_bucket_same_wrt,
+ &writebuf);
+ else
+ action = BLK_NOTFOUND;
/* replay the record for adding entries in overflow buffer */
if (action == BLK_NEEDS_REDO)
@@ -665,7 +676,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint16 ninserted = 0;
bool mod_wbuf = false;
- data = begin = XLogRecGetBlockData(record, 1, &datalen);
+ data = begin = XLogRecGetBlockData(record, 0, &datalen);
writepage = BufferGetPage(writebuf);
@@ -731,7 +742,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
}
/* replay the record for initializing overflow buffer */
- if (XLogReadBufferForRedo(record, 2, &ovflbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 1, &ovflbuf) == BLK_NEEDS_REDO)
{
Page ovflpage;
HashPageOpaque ovflopaque;
@@ -756,7 +767,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
/* replay the record for page previous to the freed overflow page */
if (!xldata->is_prev_bucket_same_wrt &&
- XLogReadBufferForRedo(record, 3, &prevbuf) == BLK_NEEDS_REDO)
+ XLogReadBufferForRedo(record, 2, &prevbuf) == BLK_NEEDS_REDO)
{
Page prevpage = BufferGetPage(prevbuf);
HashPageOpaque prevopaque = HashPageGetOpaque(prevpage);
@@ -770,11 +781,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(prevbuf);
/* replay the record for page next to the freed overflow page */
- if (XLogRecHasBlockRef(record, 4))
+ if (XLogRecHasBlockRef(record, 3))
{
Buffer nextbuf;
- if (XLogReadBufferForRedo(record, 4, &nextbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 3, &nextbuf) == BLK_NEEDS_REDO)
{
Page nextpage = BufferGetPage(nextbuf);
HashPageOpaque nextopaque = HashPageGetOpaque(nextpage);
@@ -801,7 +812,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
* index updates can be happening concurrently.
*/
/* replay the record for bitmap page */
- if (XLogReadBufferForRedo(record, 5, &mapbuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 4, &mapbuf) == BLK_NEEDS_REDO)
{
Page mappage = BufferGetPage(mapbuf);
uint32 *freep = NULL;
@@ -811,7 +822,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
freep = HashPageGetBitmap(mappage);
- data = XLogRecGetBlockData(record, 5, &datalen);
+ data = XLogRecGetBlockData(record, 4, &datalen);
bitmap_page_bit = (uint32 *) data;
CLRBIT(freep, *bitmap_page_bit);
@@ -823,11 +834,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
UnlockReleaseBuffer(mapbuf);
/* replay the record for meta page */
- if (XLogRecHasBlockRef(record, 6))
+ if (XLogRecHasBlockRef(record, 5))
{
Buffer metabuf;
- if (XLogReadBufferForRedo(record, 6, &metabuf) == BLK_NEEDS_REDO)
+ if (XLogReadBufferForRedo(record, 5, &metabuf) == BLK_NEEDS_REDO)
{
HashMetaPage metap;
Page page;
@@ -835,7 +846,7 @@ hash_xlog_squeeze_page(XLogReaderState *record)
uint32 *firstfree_ovflpage;
Size datalen;
- data = XLogRecGetBlockData(record, 6, &datalen);
+ data = XLogRecGetBlockData(record, 5, &datalen);
firstfree_ovflpage = (uint32 *) data;
page = BufferGetPage(metabuf);
@@ -871,27 +882,12 @@ hash_xlog_delete(XLogReaderState *record)
* can miss some records or show the same record multiple times.
*/
if (xldata->is_primary_bucket_page)
- action = XLogReadBufferForRedoExtended(record, 1, RBM_NORMAL, true, &deletebuf);
+ action = XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &deletebuf);
else
{
- /*
- * The cleanup lock is needed only when hot standby is active, because
- * scans cannot run before that. Skipping the read also avoids a torn
- * copy of the primary page. This record does not modify that page, so
- * it has no full-page image of it. In crash recovery, or on a standby
- * started from a base backup, the page on disk can be torn and the
- * image that repairs it can come later in the WAL.
- */
- if (HotStandbyActiveInReplay())
- {
- /*
- * we don't care for return value as the purpose of reading
- * bucketbuf is to ensure a cleanup lock on primary bucket page.
- */
- (void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf);
- }
+ bucketbuf = hash_xlog_lock_primary_bucket(record, 0, SizeOfHashDelete);
- action = XLogReadBufferForRedo(record, 1, &deletebuf);
+ action = XLogReadBufferForRedo(record, 0, &deletebuf);
}
/* replay the record for deleting entries in bucket page */
@@ -900,7 +896,7 @@ hash_xlog_delete(XLogReaderState *record)
char *ptr;
Size len;
- ptr = XLogRecGetBlockData(record, 1, &len);
+ ptr = XLogRecGetBlockData(record, 0, &len);
page = BufferGetPage(deletebuf);
diff --git a/src/backend/access/hash/hashovfl.c b/src/backend/access/hash/hashovfl.c
index dbc57ef958c..35f214767bd 100644
--- a/src/backend/access/hash/hashovfl.c
+++ b/src/backend/access/hash/hashovfl.c
@@ -580,9 +580,13 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
/* Get write-lock on metapage to update firstfree */
LockBuffer(metabuf, BUFFER_LOCK_EXCLUSIVE);
- /* This operation needs to log multiple tuples, prepare WAL for that */
+ /*
+ * This operation needs to log multiple tuples, prepare WAL for that. One
+ * extra data segment accounts for the primary bucket page's block number,
+ * appended to the record when that page is pin-only (not registered).
+ */
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 4 + nitups);
+ XLogEnsureRecordSpace(HASH_XLOG_FREE_OVFL_BUFS, 5 + nitups);
START_CRIT_SECTION();
@@ -656,6 +660,7 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
if (RelationNeedsWAL(rel))
{
xl_hash_squeeze_page xlrec;
+ BlockNumber bucket_blkno = BufferGetBlockNumber(bucketbuf);
xlrec.prevblkno = prevblkno;
xlrec.nextblkno = nextblkno;
@@ -667,45 +672,26 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
XLogRegisterData(&xlrec, SizeOfHashSqueezePage);
/*
- * bucket buffer was not changed, but still needs to be registered to
- * ensure that we can acquire a cleanup lock on it during replay.
+ * Replay needs the primary bucket block number to acquire a cleanup
+ * lock. Register it as block 0 when it is modified; otherwise append
+ * its block number to the record.
*/
- if (!is_prim_bucket_same_wrt)
- {
- uint8 flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucketbuf, flags);
- }
+ if (!(is_prim_bucket_same_wrt && mod_wbuf))
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- if (nitups > 0)
- {
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
- nitups * sizeof(OffsetNumber));
- for (int i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
- }
- else if (is_prim_bucket_same_wrt || is_prev_bucket_same_wrt)
+ if (mod_wbuf)
{
- uint8 wbuf_flags;
-
- /*
- * A write buffer needs to be registered even if no tuples are
- * added to it to ensure that we can acquire a cleanup lock on it
- * if it is the same as primary bucket buffer or update the
- * nextblkno if it is same as the previous bucket buffer.
- */
- Assert(nitups == 0);
-
- wbuf_flags = REGBUF_STANDARD;
- if (!is_prev_bucket_same_wrt)
- wbuf_flags |= REGBUF_NO_CHANGE;
- else
- Assert(mod_wbuf);
- XLogRegisterBuffer(1, wbuf, wbuf_flags);
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ if (nitups > 0)
+ {
+ XLogRegisterBufData(0, itup_offsets,
+ nitups * sizeof(OffsetNumber));
+ for (int i = 0; i < nitups; i++)
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
+ }
}
- XLogRegisterBuffer(2, ovflbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(1, ovflbuf, REGBUF_STANDARD);
/*
* If prevpage and the writepage (block in which we are moving tuples
@@ -714,18 +700,18 @@ _hash_freeovflpage(Relation rel, Buffer bucketbuf, Buffer ovflbuf,
* writepage.
*/
if (BufferIsValid(prevbuf) && !is_prev_bucket_same_wrt)
- XLogRegisterBuffer(3, prevbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(2, prevbuf, REGBUF_STANDARD);
if (BufferIsValid(nextbuf))
- XLogRegisterBuffer(4, nextbuf, REGBUF_STANDARD);
+ XLogRegisterBuffer(3, nextbuf, REGBUF_STANDARD);
- XLogRegisterBuffer(5, mapbuf, REGBUF_STANDARD);
- XLogRegisterBufData(5, &bitmapbit, sizeof(uint32));
+ XLogRegisterBuffer(4, mapbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(4, &bitmapbit, sizeof(uint32));
if (update_metap)
{
- XLogRegisterBuffer(6, metabuf, REGBUF_STANDARD);
- XLogRegisterBufData(6, &metap->hashm_firstfree, sizeof(uint32));
+ XLogRegisterBuffer(5, metabuf, REGBUF_STANDARD);
+ XLogRegisterBufData(5, &metap->hashm_firstfree, sizeof(uint32));
}
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_SQUEEZE_PAGE);
@@ -966,10 +952,12 @@ readpage:
/*
* This operation needs to log multiple tuples, prepare
- * WAL for that.
+ * WAL for that. One extra data segment accounts for the
+ * primary bucket page's block number, appended to the
+ * record when that page is pin-only (not registered).
*/
if (RelationNeedsWAL(rel))
- XLogEnsureRecordSpace(0, 3 + nitups);
+ XLogEnsureRecordSpace(0, 4 + nitups);
START_CRIT_SECTION();
@@ -998,25 +986,22 @@ readpage:
XLogRegisterData(&xlrec, SizeOfHashMovePageContents);
/*
- * bucket buffer was not changed, but still needs to
- * be registered to ensure that we can acquire a
- * cleanup lock on it during replay.
+ * If wbuf is an overflow page, the primary bucket
+ * page is not changed and we hold only a pin on it,
+ * so it is not registered. Append its block number
+ * instead, and replay takes a cleanup lock on it.
*/
if (!xlrec.is_prim_bucket_same_wrt)
- {
- int flags = REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
-
- XLogRegisterBuffer(0, bucket_buf, flags);
- }
+ XLogRegisterData(&bucket_blkno, sizeof(BlockNumber));
- XLogRegisterBuffer(1, wbuf, REGBUF_STANDARD);
- XLogRegisterBufData(1, itup_offsets,
+ XLogRegisterBuffer(0, wbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(0, itup_offsets,
nitups * sizeof(OffsetNumber));
for (i = 0; i < nitups; i++)
- XLogRegisterBufData(1, itups[i], tups_size[i]);
+ XLogRegisterBufData(0, itups[i], tups_size[i]);
- XLogRegisterBuffer(2, rbuf, REGBUF_STANDARD);
- XLogRegisterBufData(2, deletable,
+ XLogRegisterBuffer(1, rbuf, REGBUF_STANDARD);
+ XLogRegisterBufData(1, deletable,
ndeletable * sizeof(OffsetNumber));
recptr = XLogInsert(RM_HASH_ID, XLOG_HASH_MOVE_PAGE_CONTENTS);
diff --git a/src/include/access/hash_xlog.h b/src/include/access/hash_xlog.h
index 149aed69dc5..0bb0d0590f5 100644
--- a/src/include/access/hash_xlog.h
+++ b/src/include/access/hash_xlog.h
@@ -129,9 +129,13 @@ typedef struct xl_hash_split_complete
*
* This data record is used for XLOG_HASH_MOVE_PAGE_CONTENTS
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing moved tuples
- * Backup Blk 2: page from which tuples will be removed
+ * Backup Blk 0: page containing moved tuples
+ * Backup Blk 1: page from which tuples will be removed
+ *
+ * The primary bucket page is not registered. If it is not the page moved to
+ * (is_prim_bucket_same_wrt is false), the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_move_page_contents
{
@@ -149,13 +153,18 @@ typedef struct xl_hash_move_page_contents
*
* This data record is used for XLOG_HASH_SQUEEZE_PAGE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page containing tuples moved from freed overflow page
- * Backup Blk 2: freed overflow page
- * Backup Blk 3: page previous to the freed overflow page
- * Backup Blk 4: page next to the freed overflow page
- * Backup Blk 5: bitmap page containing info of freed overflow page
- * Backup Blk 6: meta page
+ * Backup Blk 0: page containing tuples moved from freed overflow page, if
+ * it is modified
+ * Backup Blk 1: freed overflow page
+ * Backup Blk 2: page previous to the freed overflow page
+ * Backup Blk 3: page next to the freed overflow page
+ * Backup Blk 4: bitmap page containing info of freed overflow page
+ * Backup Blk 5: meta page
+ *
+ * The primary bucket page is registered only as block 0, when it is the
+ * modified write page. Otherwise the block number of the primary bucket
+ * page follows the struct as a BlockNumber, and replay takes a cleanup lock
+ * on that block.
*/
typedef struct xl_hash_squeeze_page
{
@@ -179,8 +188,12 @@ typedef struct xl_hash_squeeze_page
*
* This data record is used for XLOG_HASH_DELETE
*
- * Backup Blk 0: primary bucket page
- * Backup Blk 1: page from which tuples are deleted
+ * Backup Blk 0: page from which tuples are deleted
+ *
+ * If block 0 is not the primary bucket page (is_primary_bucket_page is
+ * false), the block number of the primary bucket page follows the struct as a
+ * BlockNumber, and replay takes a cleanup lock on that block. The primary
+ * bucket page is not registered.
*/
typedef struct xl_hash_delete
{
diff --git a/src/include/access/xlog_internal.h b/src/include/access/xlog_internal.h
index bf609c3c703..ed8f488dda5 100644
--- a/src/include/access/xlog_internal.h
+++ b/src/include/access/xlog_internal.h
@@ -32,7 +32,7 @@
/*
* Each page of XLOG file has a header like this:
*/
-#define XLOG_PAGE_MAGIC 0xD122 /* can be used as WAL version indicator */
+#define XLOG_PAGE_MAGIC 0xD123 /* can be used as WAL version indicator */
typedef struct XLogPageHeaderData
{
base-commit: 70cc154f622b812c470388ae0a6694e16f388dde
--
2.54.0
v16-0002-Add-a-recovery-test-for-the-hash-WAL-pin-only-bu.patch (text/x-patch, 12.1K) download
From 9ed7b7397663f4739e3b097d8be623ea0a9621ed Mon Sep 17 00:00:00 2001
From: Greg Burd <greg@burd.me>
Date: Fri, 30 Oct 2026 10:10:03 -0400
Subject: [PATCH v16 2/2] Add a recovery test for the hash WAL pin-only bucket
page fix
Add recovery/t/062_hash_vacuum_insert_crc.pl, which exercises the
interleaving the previous commits make safe: a hash index VACUUM logging
an overflow-page delete while a concurrent INSERT changes the primary
bucket page it holds pin-only, with wal_consistency_checking='hash'.
The test adds a general, test-only injection point in
XLogRecordAssemble(), right after the record CRC is computed and before
the record is copied into the WAL buffers. Its argument names the
record as "rmid/info/mainlen" so a test can wait on exactly one kind of
record; here the test waits on the overflow-page XLOG_HASH_DELETE (whose
main data carries the appended primary bucket block number) while VACUUM
holds the primary bucket page pin-only, then lets an INSERT change that
page, then crashes and checks that pg_waldump and crash recovery both
accept the WAL with no "incorrect resource manager data checksum".
Before 27caf4ca5ae5 and this rework, the record's CRC was computed over
the concurrently-modified primary bucket page and replay failed; the
injection point makes that window deterministic so the case is covered
from now on.
Author: Greg Burd <greg@burd.me>
Co-authored-by: Vignesh C <vignesh21@gmail.com>
Reviewed-by: Amit Kapila <amit.kapila16@gmail.com>
Reviewed-by: Joao Rito <joaovictor.rito@gmail.com>
Discussion: https://postgr.es/m/CALDaNm14vRb2TZWyhjSHx=SyT7R=e7+aCkrmXuojDwWEe40JpQ@mail.gmail.com
---
src/backend/access/transam/xloginsert.c | 22 ++
src/test/recovery/meson.build | 1 +
.../recovery/t/062_hash_vacuum_insert_crc.pl | 191 ++++++++++++++++++
3 files changed, 214 insertions(+)
create mode 100644 src/test/recovery/t/062_hash_vacuum_insert_crc.pl
diff --git a/src/backend/access/transam/xloginsert.c b/src/backend/access/transam/xloginsert.c
index 251688e37fd..ae7d00da91f 100644
--- a/src/backend/access/transam/xloginsert.c
+++ b/src/backend/access/transam/xloginsert.c
@@ -39,6 +39,7 @@
#include "replication/origin.h"
#include "storage/bufmgr.h"
#include "storage/proc.h"
+#include "utils/injection_point.h"
#include "utils/memutils.h"
#include "utils/pgstat_internal.h"
#include "utils/rel.h"
@@ -988,6 +989,27 @@ XLogRecordAssemble(RmgrId rmid, uint8 info,
for (rdt = hdr_rdt.next; rdt != NULL; rdt = rdt->next)
COMP_CRC32C(rdata_crc, rdt->data, rdt->len);
+ /*
+ * Test hook: let a test modify a buffer after the record's CRC has been
+ * computed but before the record is copied into the WAL buffers, to
+ * reproduce the window in which a concurrently modified, pin-only
+ * registered buffer could make the on-disk CRC not match the record. The
+ * argument names the record as "rmid/info/mainlen" (resource manager, its
+ * info bits, and the length of the main data) so a test can wait on
+ * exactly one kind of record. This runs inside a critical section, so it
+ * must not allocate; it fires only in a backend that loaded the point
+ * beforehand.
+ */
+#ifdef USE_INJECTION_POINTS
+ {
+ char pointarg[24];
+
+ snprintf(pointarg, sizeof(pointarg), "%d/%02X/" UINT64_FORMAT,
+ rmid, info, mainrdata_len);
+ INJECTION_POINT_CACHED("xlog-assemble-after-crc", pointarg);
+ }
+#endif
+
/*
* Ensure that the XLogRecord is not too large.
*
diff --git a/src/test/recovery/meson.build b/src/test/recovery/meson.build
index cb3df6ed895..4a3a3686ce4 100644
--- a/src/test/recovery/meson.build
+++ b/src/test/recovery/meson.build
@@ -70,6 +70,7 @@ tests += {
't/059_remote_apply_status_interval.pl',
't/060_multixact_crashed_updater.pl',
't/061_recovery_target_prefetch.pl',
+ 't/062_hash_vacuum_insert_crc.pl',
],
},
}
diff --git a/src/test/recovery/t/062_hash_vacuum_insert_crc.pl b/src/test/recovery/t/062_hash_vacuum_insert_crc.pl
new file mode 100644
index 00000000000..89f7611af12
--- /dev/null
+++ b/src/test/recovery/t/062_hash_vacuum_insert_crc.pl
@@ -0,0 +1,191 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that the WAL record written by hash index VACUUM for an overflow page is
+# intact when a concurrent INSERT changes the primary bucket page.
+#
+# hashbucketcleanup() keeps only a pin on the primary bucket page while it
+# walks the overflow chain. Before the hash WAL rework it registered that page
+# (REGBUF_STANDARD | REGBUF_NO_IMAGE | REGBUF_NO_CHANGE) with the
+# XLOG_HASH_DELETE record it writes for each overflow page. With
+# wal_consistency_checking enabled for the hash resource manager,
+# XLogRecordAssemble() included a full image of every registered block, so it
+# read the unlocked primary bucket page. If an INSERT added a tuple to that
+# page after the record's CRC was computed but before the page was copied into
+# the WAL buffers, the record was written with a CRC that did not match its
+# contents, and replay stopped at it with "incorrect resource manager data
+# checksum".
+#
+# The window is a few microseconds wide, so the test widens it with an
+# injection point in XLogRecordAssemble(), placed right after the CRC is
+# computed. It is attached to the VACUUM session only and matches just the
+# overflow-page delete, identified by "rmgr id/xl_info/main-data length". The
+# point still fires after the fix, so the test exercises the same interleaving
+# on a correct server.
+#
+# The assertions state the correct behavior (all WAL is valid and replays), so
+# the test fails while the bug exists.
+
+use strict;
+use warnings FATAL => 'all';
+
+use IPC::Run;
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+ plan skip_all => 'Injection points not supported by this build';
+}
+
+my $node = PostgreSQL::Test::Cluster->new('primary');
+$node->init;
+$node->append_conf(
+ 'postgresql.conf', qq{
+wal_consistency_checking = 'hash'
+autovacuum = off
+fsync = off
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+ plan skip_all => 'Extension injection_points not installed';
+}
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+
+my $hash_rmid = $node->safe_psql('postgres',
+ q{SELECT rm_id FROM pg_get_wal_resource_managers() WHERE rm_name = 'Hash'}
+);
+
+# Build a single bucket whose primary page stays live and whose overflow page
+# is all dead, so VACUUM logs an XLOG_HASH_DELETE for the overflow page only:
+# the primary page has no dead index entries, so no delete record is written
+# for it, and the only consistency-checked hash DELETE in the window is the
+# overflow one, logged while the primary page is held pin-only. All rows share
+# the key, so they land in one bucket; the first batch fills most of the
+# primary page and stays live, the second spills onto the overflow page and is
+# deleted. Free slots are left on the primary page so the concurrent INSERT
+# below lands there.
+#
+# hashbuild() sizes the index from estimate_rel_size() on the heap, which for a
+# table that has never been vacuumed applies a floor of 10 pages. Vacuuming
+# first sets reltuples to 0, so the estimate is believed and the index starts
+# with the minimum of 2 buckets.
+$node->safe_psql(
+ 'postgres', q{
+CREATE TABLE hash_t (k int, tag int) WITH (autovacuum_enabled = false);
+VACUUM hash_t;
+CREATE INDEX hash_i ON hash_t USING hash (k);
+INSERT INTO hash_t SELECT 1, 0 FROM generate_series(1, 390);
+INSERT INTO hash_t SELECT 1, 1 FROM generate_series(1, 210);
+DELETE FROM hash_t WHERE tag = 1;
+});
+
+# Premise: metapage, two bucket pages, a bitmap page and one overflow page.
+is( $node->safe_psql(
+ 'postgres',
+ q{SELECT pg_relation_size('hash_i') / current_setting('block_size')::int}
+ ),
+ '5',
+ 'premise: the index has a primary bucket page and one overflow page');
+
+# Start from a checkpoint, so crash recovery replays everything below and
+# pg_waldump has a record boundary to start from.
+$node->safe_psql('postgres', 'CHECKPOINT');
+my $start_lsn = $node->safe_psql('postgres', 'SELECT pg_current_wal_lsn()');
+
+# The VACUUM session. The point is attached to this session only and must be
+# loaded before the critical section in which it runs.
+#
+# Wait on the XLOG_HASH_DELETE record for the overflow page, not the one for
+# the primary page. Both are hash records (rm id $hash_rmid) with info 0x92
+# (XLOG_HASH_DELETE 0x90 | XLR_CHECK_CONSISTENCY 0x02). They differ in main
+# data length: the primary-page delete carries just xl_hash_delete
+# (SizeOfHashDelete, two bools = 2 bytes), while the overflow-page delete also
+# appends the primary bucket page's block number (a 4-byte BlockNumber), for 6
+# bytes. Waiting on the 6-byte one parks VACUUM while it holds the primary
+# bucket page pin-only, which is the page the INSERT below changes.
+my $overflow_delete = "$hash_rmid/92/6";
+my $vacuum = $node->background_psql('postgres');
+my $vacuum_pid = $vacuum->query_safe('SELECT pg_backend_pid()');
+$vacuum->query_safe(q{SELECT injection_points_set_local()});
+$vacuum->query_safe(
+ qq{SELECT injection_points_attach('xlog-assemble-after-crc', 'wait', '$overflow_delete')}
+);
+$vacuum->query_safe(
+ q{SELECT injection_points_load('xlog-assemble-after-crc')});
+$vacuum->query_until(
+ qr/starting_vacuum/,
+ q(\echo starting_vacuum
+VACUUM (INDEX_CLEANUP on) hash_t;
+));
+
+# VACUUM has removed the dead entries from the primary page, released its lock
+# (keeping the pin), and is now logging the removal from the overflow page: the
+# CRC of that record is computed and the unlocked primary page is not yet
+# copied.
+$node->poll_query_until('postgres',
+ "SELECT wait_event = 'xlog-assemble-after-crc' FROM pg_stat_activity WHERE pid = $vacuum_pid"
+) or die "VACUUM did not reach the injection point";
+note('VACUUM is between computing the CRC and copying the record');
+
+# Now there is room in the primary page, so this INSERT changes it while VACUUM
+# holds it pin-only during the overflow delete.
+$node->safe_psql('postgres', q{INSERT INTO hash_t VALUES (1, 0)});
+
+$node->safe_psql('postgres',
+ q{SELECT injection_points_wakeup('xlog-assemble-after-crc')});
+$vacuum->quit;
+
+my $end_lsn =
+ $node->safe_psql('postgres', 'SELECT pg_current_wal_insert_lsn()');
+$node->poll_query_until('postgres',
+ "SELECT pg_current_wal_flush_lsn() >= '$end_lsn'")
+ or die "timed out waiting for WAL flush";
+
+# The first and the last WAL segment of the range. With only --path, pg_waldump
+# takes the WAL segment size from the first file readdir() returns, which can be
+# a zero-filled, unused segment, and then fails with "invalid WAL segment size".
+# Naming the segments makes it read the size from the first of them.
+my $start_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$start_lsn')");
+my $end_seg =
+ $node->safe_psql('postgres', "SELECT pg_walfile_name('$end_lsn')");
+
+# Crash, so that start-up has to replay (and CRC-check) the workload.
+$node->stop('immediate');
+
+# 1. Every record in the range must have a valid CRC. pg_waldump verifies it
+# for every record it reads, whatever the --rmgr filter.
+my $stderr;
+my $ok = IPC::Run::run(
+ [
+ 'pg_waldump',
+ '--path' => $node->data_dir . '/pg_wal',
+ '--start' => $start_lsn,
+ '--end' => $end_lsn,
+ '--rmgr' => 'Hash',
+ $start_seg, $end_seg,
+ ],
+ '>' => '/dev/null',
+ '2>' => \$stderr);
+
+ok($ok, 'pg_waldump reads the whole workload without errors');
+unlike(
+ $stderr,
+ qr/incorrect resource manager data checksum/,
+ 'no WAL record has a mismatching CRC');
+
+# 2. Crash recovery must replay it without complaint.
+my $log_offset = -s $node->logfile;
+$node->start;
+my $log = slurp_file($node->logfile, $log_offset);
+unlike(
+ $log,
+ qr/incorrect resource manager data checksum|inconsistent page found/,
+ 'crash recovery replays the workload without CRC or consistency errors');
+
+$node->stop;
+done_testing();
--
2.54.0
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-17 11:20 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-17 20:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-18 07:13 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-18 08:33 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-18 13:11 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-18 18:24 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-20 15:01 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-21 18:39 ` shihao zhong <zhong950419@gmail.com>
0 siblings, 0 replies; 34+ messages in thread
From: shihao zhong @ 2026-11-21 18:39 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; +Cc: Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>; pgsql-hackers@lists.postgresql.org, vignesh C <vignesh21@gmail.com>; Amit Kapila <amit.kapila16@gmail.com>; Joao Rito <joaovictor.rito@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>
Hi Greg,
I think v16 is pretty good.
Two small things:
1. In hash_xlog_squeeze_page(), block 0 is now registered only when
the write page is modified. So inside the BLK_NEEDS_REDO block,
mod_wbuf always ends up true. The Assert in the ntups == 0 can be change.
2. pg_waldump no longer shows the primary bucket block.
I had attached proposed fix in this email
Thanks,
Shihao
Attachments:
nocfbot-0001-hash-tighten-squeeze-assert-and-desc.patch (application/octet-stream, 3.5K) download
From 6a5c18cdfb13c1f083f77ceb3fe28c81c7967d00 Mon Sep 17 00:00:00 2001
From: shihao zhong <zhong950419@gmail.com>
Date: Sat, 21 Nov 2026 13:00:56 -0500
Subject: [PATCH] Hash: tighten squeeze redo Assert, show primary bucket block
in desc
hash_xlog_squeeze_page() registers the write page as block 0 only when
it is modified. So when it replays a record with no tuples, the write
page must be the previous page, and the Assert can say so.
Since the primary bucket page is no longer registered when the
operation holds only a pin on it, pg_waldump did not show it at all.
Print its block number for DELETE, MOVE_PAGE_CONTENTS and SQUEEZE_PAGE
when the record carries it.
---
src/backend/access/hash/hash_xlog.c | 8 ++++----
src/backend/access/rmgrdesc/hashdesc.c | 21 +++++++++++++++++++++
2 files changed, 25 insertions(+), 4 deletions(-)
diff --git a/src/backend/access/hash/hash_xlog.c b/src/backend/access/hash/hash_xlog.c
index f4816486618..430c7e8c879 100644
--- a/src/backend/access/hash/hash_xlog.c
+++ b/src/backend/access/hash/hash_xlog.c
@@ -709,11 +709,11 @@ hash_xlog_squeeze_page(XLogReaderState *record)
else
{
/*
- * Ensure that the required flags are set when there are no
- * tuples. See _hash_freeovflpage().
+ * The write page is registered only when it is modified, so with
+ * no tuples it must be the previous page, whose nextblkno is
+ * updated below. See _hash_freeovflpage().
*/
- Assert(xldata->is_prim_bucket_same_wrt ||
- xldata->is_prev_bucket_same_wrt);
+ Assert(xldata->is_prev_bucket_same_wrt);
}
/*
diff --git a/src/backend/access/rmgrdesc/hashdesc.c b/src/backend/access/rmgrdesc/hashdesc.c
index 593013afe9c..e16fc2a1539 100644
--- a/src/backend/access/rmgrdesc/hashdesc.c
+++ b/src/backend/access/rmgrdesc/hashdesc.c
@@ -16,6 +16,24 @@
#include "access/hash_xlog.h"
+/*
+ * Append the block number of the primary bucket page, if the record carries
+ * it in its main data after a struct of rec_size bytes. It does so when the
+ * page is not registered because the operation holds only a pin on it.
+ */
+static void
+hash_desc_primary_bucket(StringInfo buf, XLogReaderState *record, Size rec_size)
+{
+ if (XLogRecGetDataLen(record) >= rec_size + sizeof(BlockNumber))
+ {
+ BlockNumber bucket_blkno;
+
+ memcpy(&bucket_blkno, XLogRecGetData(record) + rec_size,
+ sizeof(BlockNumber));
+ appendStringInfo(buf, ", primary_blkno %u", bucket_blkno);
+ }
+}
+
void
hash_desc(StringInfo buf, XLogReaderState *record)
{
@@ -83,6 +101,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
appendStringInfo(buf, "ntups %d, is_primary %c",
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F');
+ hash_desc_primary_bucket(buf, record, SizeOfHashMovePageContents);
break;
}
case XLOG_HASH_SQUEEZE_PAGE:
@@ -95,6 +114,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
xlrec->ntups,
xlrec->is_prim_bucket_same_wrt ? 'T' : 'F',
xlrec->is_prev_bucket_same_wrt ? 'T' : 'F');
+ hash_desc_primary_bucket(buf, record, SizeOfHashSqueezePage);
break;
}
case XLOG_HASH_DELETE:
@@ -104,6 +124,7 @@ hash_desc(StringInfo buf, XLogReaderState *record)
appendStringInfo(buf, "clear_dead_marking %c, is_primary %c",
xlrec->clear_dead_marking ? 'T' : 'F',
xlrec->is_primary_bucket_page ? 'T' : 'F');
+ hash_desc_primary_bucket(buf, record, SizeOfHashDelete);
break;
}
case XLOG_HASH_UPDATE_META_PAGE:
--
2.37.1 (Apple Git-137.1)
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-12 06:39 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-13 10:21 ` RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-14 15:02 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-17 11:20 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-17 20:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-18 07:13 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
@ 2026-11-18 11:47 ` Greg Burd <greg@burd.me>
1 sibling, 0 replies; 34+ messages in thread
From: Greg Burd @ 2026-11-18 11:47 UTC (permalink / raw)
To: Amit Kapila <amit.kapila16@gmail.com>; +Cc: vignesh C <vignesh21@gmail.com>; Hayato Kuroda <kuroda.hayato@fujitsu.com>; Joao Rito <joaovictor.rito@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
On Wednesday, November 18th, 2026 at 2:13 AM, Amit Kapila <amit.kapila16@gmail.com> wrote:
> On Wed, Nov 18, 2026 at 1:51 AM Greg Burd <greg@burd.me> wrote:
> >
> > Amit, Vignesh,
> >
> > Agreed, and thanks Vignesh for splitting it out. v13 is what I had in
> > mind: the torn-page read fix on its own, backpatchable, with the
> > recovery test and the HEAD-only rework (dropping the pin-only
> > registration, removing REGBUF_NO_CHANGE) left for a separate commit on
> > master once this is in.
> >
>
> Pushed. Next, I suggest we can work on the patch for "dropping the
> pin-only registration". Once that is committed, we can move to
> removing REGBUF_NO_CHANGE.
Thanks for committing that Amit!
> --
> With Regards,
> Amit Kapila.
on to the next bit.
-greg
^ permalink raw reply [nested|flat] 34+ messages in thread
* RE: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-12 10:41 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2 siblings, 0 replies; 34+ messages in thread
From: Hayato Kuroda (Fujitsu) @ 2026-11-12 10:41 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; Amit Kapila <amit.kapila16@gmail.com>; +Cc: shihao zhong <zhong950419@gmail.com>; vignesh C <vignesh21@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org <pgsql-hackers@lists.postgresql.org>
Hi,
I started to study the thread. Here are minor comments for 0002.
I understood the refactoring must be done master-only.
01.
```
+static Buffer
+hash_xlog_lock_bucket(XLogReaderState *record, uint8 block_id, Size rec_size)
```
I think the function name is too general. IIUC the function intends to lock a
primary page, but it's not described in the function name. How about renaming to
"hash_xlog_lock_primary_bucket" or similar?
02.
```
+ /* block 0 is absent if the primary bucket page is not modified */
```
I felt this comment can be more friendly like:
```
/*
* If the primary bucket page is modified, it is registered as block 0
* and read for REDO. Otherwise, acquire its cleanup lock separately.
*/
```
Best regards,
Hayato Kuroda
FUJITSU LIMITED
^ permalink raw reply [nested|flat] 34+ messages in thread
* Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE)
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 11:48 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 21:11 ` Re: Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
@ 2026-11-12 13:23 ` vignesh C <vignesh21@gmail.com>
2 siblings, 0 replies; 34+ messages in thread
From: vignesh C @ 2026-11-12 13:23 UTC (permalink / raw)
To: Greg Burd <greg@burd.me>; +Cc: Amit Kapila <amit.kapila16@gmail.com>; shihao zhong <zhong950419@gmail.com>; Michael Paquier <michael@paquier.xyz>; Jeff Davis <pgsql@j-davis.com>; Alexander Lakhin <exclusion@gmail.com>; pgsql-hackers@lists.postgresql.org
On Thu, 12 Nov 2026 at 02:41, Greg Burd <greg@burd.me> wrote:
>
> Since the bug is pre-existing, the fix is patch 0001: it stands on its
> own against master, applies with or without the rework, and (the
> back-branch question aside)
We will have to back patch till the PG15 version. I could reproduce
the issue in all the supported branches and the
HotStandbyActiveInReplay changes at [1] fixes the issue.
One small improvement could be done to the patches,
hash_xlog_move_page_contents, hash_xlog_squeeze_page and
hash_xlog_delete all have the below same code, can we use a helper
static function for this:
/*
* The cleanup lock on the primary bucket page serializes replay
* against scans on a hot standby, which pin the page for their whole
* duration. Scans can run only once hot standby accepts queries, so
* until then we need not read or lock the page. Skipping the read
* also sidesteps a torn copy of the page whose repairing full-page
* image comes later in the WAL: that hazard exists only before
* consistency is reached, and queries are accepted only after that,
* so once HotStandbyActiveInReplay() is true any earlier image has
* already been replayed.
*/
if (HotStandbyActiveInReplay())
(void) XLogReadBufferForRedoExtended(record, 0, RBM_NORMAL, true, &bucketbuf)
@Gregory Burd Could you post the 0001 patches for the torn-page issue,
covering branches up to PG15? We can make the patch ready for commit.
[1] - https://www.postgresql.org/message-id/CALDaNm3ZudVo%2BNT6HKA%2BkPbmXmCuKv%2BZw95Do5G5%2BEUE9GGn%3Dg%...
Regards,
Vignesh
^ permalink raw reply [nested|flat] 34+ messages in thread
end of thread, other threads:[~2026-11-21 18:39 UTC | newest]
Thread overview: 34+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-10-29 16:12 Hash index: stop registering pin-only bucket pages in WAL (remove REGBUF_NO_CHANGE) Greg Burd <greg@burd.me>
2026-10-30 09:18 ` vignesh C <vignesh21@gmail.com>
2026-10-30 11:48 ` vignesh C <vignesh21@gmail.com>
2026-10-30 17:21 ` Greg Burd <greg@burd.me>
2026-10-31 11:32 ` Amit Kapila <amit.kapila16@gmail.com>
2026-11-03 16:11 ` Greg Burd <greg@burd.me>
2026-11-06 10:44 ` Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 03:03 ` shihao zhong <zhong950419@gmail.com>
2026-11-11 09:28 ` vignesh C <vignesh21@gmail.com>
2026-11-11 11:49 ` Amit Kapila <amit.kapila16@gmail.com>
2026-11-11 18:14 ` Greg Burd <greg@burd.me>
2026-11-11 21:11 ` Greg Burd <greg@burd.me>
2026-11-12 06:39 ` vignesh C <vignesh21@gmail.com>
2026-11-12 13:25 ` Greg Burd <greg@burd.me>
2026-11-12 16:12 ` Joao Rito <joaovictor.rito@gmail.com>
2026-11-13 10:41 ` vignesh C <vignesh21@gmail.com>
2026-11-13 14:48 ` João Rito <joaovictor.rito@gmail.com>
2026-11-13 10:21 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-13 19:11 ` Greg Burd <greg@burd.me>
2026-11-14 15:02 ` Greg Burd <greg@burd.me>
2026-11-14 20:35 ` Greg Burd <greg@burd.me>
2026-11-16 10:52 ` Amit Kapila <amit.kapila16@gmail.com>
2026-11-16 11:30 ` Greg Burd <greg@burd.me>
2026-11-17 11:20 ` vignesh C <vignesh21@gmail.com>
2026-11-17 20:21 ` Greg Burd <greg@burd.me>
2026-11-18 07:13 ` Amit Kapila <amit.kapila16@gmail.com>
2026-11-18 08:33 ` vignesh C <vignesh21@gmail.com>
2026-11-18 13:11 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-18 18:24 ` Greg Burd <greg@burd.me>
2026-11-20 15:01 ` Greg Burd <greg@burd.me>
2026-11-21 18:39 ` shihao zhong <zhong950419@gmail.com>
2026-11-18 11:47 ` Greg Burd <greg@burd.me>
2026-11-12 10:41 ` Hayato Kuroda (Fujitsu) <kuroda.hayato@fujitsu.com>
2026-11-12 13:23 ` vignesh C <vignesh21@gmail.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox