WAL record CRC calculated incorrectly because of underlying buffer modification
WAL record CRC calculated incorrectly because of underlying buffer modification
Hello hackers,
I've investigated a recent buildfarm failure:
https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=dodo&dt=2024-05-02%2006%3A40%3A36
where the test failed due to a CRC error:
2024-05-02 17:08:18.401 ACST [3406:7] LOG: incorrect resource manager data checksum in record at 0/F14D7A60
(Chipmunk produced similar errors as well:
https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=chipmunk&dt=2022-08-25%2019%3A40%3A11
https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=chipmunk&dt=2024-03-22%2003%3A20%3A39
https://buildfarm.postgresql.org/cgi-bin/show_log.pl?nm=chipmunk&dt=2023-08-19%2006%3A43%3A20
)
and discovered that XLogRecordAssemble() calculates CRC over a buffer,
that might be modified by another process.
With the attached patch applied, the following test run:
echo "
autovacuum_naptime = 1
autovacuum_vacuum_threshold = 1
wal_consistency_checking = all
" >/tmp/temp.config
for ((i=1;i<=100;i++)); do echo "iteration $i"; TEMP_CONFIG=/tmp/temp.config TESTS="test_setup hash_index" make
check-tests -s || break; done
fails for me on iterations 7, 10, 17:
ok 1 - test_setup 2557 ms
not ok 2 - hash_index 24719 ms
# (test process exited with exit code 2)
postmaster.log contains:
2024-05-10 12:46:44.320 UTC checkpointer[1881151] LOG: checkpoint starting: immediate force wait
2024-05-10 12:46:44.365 UTC checkpointer[1881151] LOG: checkpoint complete: wrote 41 buffers (0.3%); 0 WAL file(s)
added, 0 removed, 26 recycled; write=0.001 s, sync=0.001 s, total=0.046 s; sync files=0, longest=0.000 s, average=0.000
s; distance=439134 kB, estimate=527137 kB; lsn=0/3CE131F0, redo lsn=0/3CE13198
TRAP: failed Assert("memcmp(block1_ptr, block1_copy, block1_len) == 0"), File: "xloginsert.c", Line: 949, PID: 1881271
ExceptionalCondition at assert.c:52:13
XLogRecordAssemble at xloginsert.c:953:1
XLogInsert at xloginsert.c:520:9
hashbucketcleanup at hash.c:844:14
hashbulkdelete at hash.c:558:3
index_bulk_delete at indexam.c:760:1
vac_bulkdel_one_index at vacuum.c:2498:10
lazy_vacuum_one_index at vacuumlazy.c:2443:10
lazy_vacuum_all_indexes at vacuumlazy.c:2026:26
lazy_vacuum at vacuumlazy.c:1944:10
lazy_scan_heap at vacuumlazy.c:1050:3
heap_vacuum_rel at vacuumlazy.c:503:2
vacuum_rel at vacuum.c:2214:2
vacuum at vacuum.c:622:8
autovacuum_do_vac_analyze at autovacuum.c:3102:2
do_autovacuum at autovacuum.c:2425:23
AutoVacWorkerMain at autovacuum.c:1569:3
pgarch_die at pgarch.c:846:1
StartChildProcess at postmaster.c:3929:5
StartAutovacuumWorker at postmaster.c:3997:12
process_pm_pmsignal at postmaster.c:3809:3
ServerLoop at postmaster.c:1667:5
BackgroundWorkerInitializeConnection at postmaster.c:4156:1
main at main.c:184:3
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0x80)[0x7fc71a8d7e40]
postgres: autovacuum worker regression(_start+0x25)[0x556a8631a5e5]
2024-05-10 12:46:45.038 UTC checkpointer[1881151] LOG: checkpoint starting: immediate force wait
2024-05-10 12:46:45.965 UTC autovacuum worker[1881275] LOG: automatic analyze of table "regression.pg_catalog.pg_attribute"
avg read rate: 0.000 MB/s, avg write rate: 5.409 MB/s
buffer usage: 1094 hits, 0 misses, 27 dirtied
system usage: CPU: user: 0.01 s, system: 0.00 s, elapsed: 0.03 s
2024-05-10 12:46:46.892 UTC postmaster[1881150] LOG: server process (PID 1881271) was terminated by signal 6: Aborted
2024-05-10 12:46:46.892 UTC postmaster[1881150] DETAIL: Failed process was running: autovacuum: VACUUM ANALYZE
public.hash_cleanup_heap
(This can be reproduced with 027_stream_regress, of course, but it would
take more time.)
Best regards,
AlexanderRe: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2024-05-10 16:00:01 +0300, Alexander Lakhin wrote: > and discovered that XLogRecordAssemble() calculates CRC over a buffer, > that might be modified by another process. If, with "might", you mean that it's legitimate for that buffer to be modified, I don't think so. The bug is that something is modifying the buffer despite it being exclusively locked. I.e. what we likely have here is a bug somewhere in the hash index code. Greetings, Andres Freund
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
On Sat, May 11, 2024 at 3:57 AM Andres Freund wrote:
> On 2024-05-10 16:00:01 +0300, Alexander Lakhin wrote:
> > and discovered that XLogRecordAssemble() calculates CRC over a buffer,
> > that might be modified by another process.
>
> If, with "might", you mean that it's legitimate for that buffer to be
> modified, I don't think so. The bug is that something is modifying the buffer
> despite it being exclusively locked.
>
> I.e. what we likely have here is a bug somewhere in the hash index code.
I don't have a good grip on the higher level locking protocols of
hash.c, but one microscopic thing jumps out:
/*
* 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 (!xlrec.is_primary_bucket_page)
{
uint8 flags = REGBUF_STANDARD |
REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
XLogRegisterBuffer(0, bucket_buf, flags);
}
That registers a buffer that is pinned but not content-locked, and we
tell xloginsert.c not to copy its image into the WAL, but it does it
anyway because:
/*
* If needs_backup is true or WAL checking is enabled for current
* resource manager, log a full-page write for the current block.
*/
include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
So I guess it copies the image on dodo, which has:
'PG_TEST_EXTRA' => 'ssl ldap
kerberos wal_consistency_checking libpq_encryption xid_wraparound'
Perhaps a no-image, no-change registered buffer should not be
including an image, even for XLR_CHECK_CONSISTENCY? It's actually
useless for consistency checking too I guess, this issue aside,
because it doesn't change anything so there is nothing to check.
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Alexander Lakhin <exclusion@gmail.com>
Дата:
Hello Thomas and Andres,
Thank you for looking at this!
11.05.2024 06:26, Thomas Munro wrote:
> On Sat, May 11, 2024 at 3:57 AM Andres Freund wrote:
>> On 2024-05-10 16:00:01 +0300, Alexander Lakhin wrote:
>>> and discovered that XLogRecordAssemble() calculates CRC over a buffer,
>>> that might be modified by another process.
>> If, with "might", you mean that it's legitimate for that buffer to be
>> modified, I don't think so. The bug is that something is modifying the buffer
>> despite it being exclusively locked.
>>
>> I.e. what we likely have here is a bug somewhere in the hash index code.
> I don't have a good grip on the higher level locking protocols of
> hash.c, but one microscopic thing jumps out:
>
> /*
> * 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 (!xlrec.is_primary_bucket_page)
> {
> uint8 flags = REGBUF_STANDARD |
> REGBUF_NO_IMAGE | REGBUF_NO_CHANGE;
>
> XLogRegisterBuffer(0, bucket_buf, flags);
> }
>
> That registers a buffer that is pinned but not content-locked, and we
> tell xloginsert.c not to copy its image into the WAL, but it does it
> anyway because:
>
> /*
> * If needs_backup is true or WAL checking is enabled for current
> * resource manager, log a full-page write for the current block.
> */
> include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
>
> So I guess it copies the image on dodo, which has:
>
> 'PG_TEST_EXTRA' => 'ssl ldap
> kerberos wal_consistency_checking libpq_encryption xid_wraparound'
>
> Perhaps a no-image, no-change registered buffer should not be
> including an image, even for XLR_CHECK_CONSISTENCY? It's actually
> useless for consistency checking too I guess, this issue aside,
> because it doesn't change anything so there is nothing to check.
Yes, I think something wrong is here. I've reduced the reproducer to:
cat << 'EOF' | psql
CREATE TABLE hash_cleanup_heap(keycol INT);
CREATE INDEX hash_cleanup_index on hash_cleanup_heap USING HASH (keycol);
BEGIN;
INSERT INTO hash_cleanup_heap SELECT 1 FROM generate_series(1, 500) as i;
ROLLBACK;
EOF
cat << 'EOF' | psql &
INSERT INTO hash_cleanup_heap SELECT 1 FROM generate_series(1, 500) as i;
DROP TABLE hash_cleanup_heap;
EOF
cat << 'EOF' | psql &
SELECT pg_sleep(random() / 20);
VACUUM hash_cleanup_heap;
EOF
wait
grep 'TRAP:' server.log
("wal_consistency_checking = all" and the xloginsert patch are still required)
and with additional logging I see:
2024-05-11 03:45:23.424 UTC|law|regression|663ee9d3.1f96dd|LOG: !!!hashbucketcleanup| scan page buf: 1832
2024-05-11 03:45:23.424 UTC|law|regression|663ee9d3.1f96dd|CONTEXT: while vacuuming index "hash_cleanup_index" of
relation "public.hash_cleanup_heap"
2024-05-11 03:45:23.424 UTC|law|regression|663ee9d3.1f96dd|STATEMENT: VACUUM hash_cleanup_heap;
2024-05-11 03:45:23.424 UTC|law|regression|663ee9d3.1f96de|LOG: !!!_hash_doinsert| _hash_getbucketbuf_from_hashkey: 1822
2024-05-11 03:45:23.424 UTC|law|regression|663ee9d3.1f96de|STATEMENT: INSERT INTO hash_cleanup_heap SELECT 1 FROM
generate_series(1, 500) as i;
2024-05-11 03:45:23.424 UTC|law|regression|663ee9d3.1f96dd|LOG: !!!hashbucketcleanup| xlrec.is_primary_bucket_page: 0,
buf: 1832, bucket_buf: 1822
2024-05-11 03:45:23.424 UTC|law|regression|663ee9d3.1f96dd|CONTEXT: while vacuuming index "hash_cleanup_index" of
relation "public.hash_cleanup_heap"
2024-05-11 03:45:23.424 UTC|law|regression|663ee9d3.1f96dd|STATEMENT: VACUUM hash_cleanup_heap;
2024-05-11 03:45:23.424 UTC|law|regression|663ee9d3.1f96de|LOG: !!!_hash_doinsert| _hash_relbuf(rel, 1822)
2024-05-11 03:45:23.424 UTC|law|regression|663ee9d3.1f96de|STATEMENT: INSERT INTO hash_cleanup_heap SELECT 1 FROM
generate_series(1, 500) as i;
TRAP: failed Assert("memcmp(block1_ptr, block1_copy, block1_len) == 0"), File: "xloginsert.c", Line: 949, PID: 2070237
Best regards,
Alexander
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
On Sat, May 11, 2024 at 4:00 PM Alexander Lakhin wrote: > 11.05.2024 06:26, Thomas Munro wrote: > > Perhaps a no-image, no-change registered buffer should not be > > including an image, even for XLR_CHECK_CONSISTENCY? It's actually > > useless for consistency checking too I guess, this issue aside, > > because it doesn't change anything so there is nothing to check. > > Yes, I think something wrong is here. I've reduced the reproducer to: Does it reproduce if you do this? - include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0; + include_image = needs_backup || + ((info & XLR_CHECK_CONSISTENCY) != 0 && + (regbuf->flags & REGBUF_NO_CHANGE) == 0); Unfortunately the back branches don't have that new flag from 00d7fb5e so, even if this is the right direction (not sure, I don't understand this clean registered buffer trick) then ... but wait, why are there are no failures like this in the back branches (yet at least)? Does your reproducer work for 16? I wonder if something relevant changed recently, like f56a9def. CC'ing Michael and Amit K for info.
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Alexander Lakhin <exclusion@gmail.com>
Дата:
11.05.2024 07:25, Thomas Munro wrote: > On Sat, May 11, 2024 at 4:00 PM Alexander Lakhin wrote: >> 11.05.2024 06:26, Thomas Munro wrote: >>> Perhaps a no-image, no-change registered buffer should not be >>> including an image, even for XLR_CHECK_CONSISTENCY? It's actually >>> useless for consistency checking too I guess, this issue aside, >>> because it doesn't change anything so there is nothing to check. >> Yes, I think something wrong is here. I've reduced the reproducer to: > Does it reproduce if you do this? > > - include_image = needs_backup || (info & > XLR_CHECK_CONSISTENCY) != 0; > + include_image = needs_backup || > + ((info & XLR_CHECK_CONSISTENCY) != 0 && > + (regbuf->flags & REGBUF_NO_CHANGE) == 0); No, it doesn't (at least with the latter, more targeted reproducer). > Unfortunately the back branches don't have that new flag from 00d7fb5e > so, even if this is the right direction (not sure, I don't understand > this clean registered buffer trick) then ... but wait, why are there > are no failures like this in the back branches (yet at least)? Does > your reproducer work for 16? I wonder if something relevant changed > recently, like f56a9def. CC'ing Michael and Amit K for info. Maybe it's hard to hit (autovacuum needs to process the index page in a narrow time frame), but locally I could reproduce the issue even on ac27c74de(~1 too) from 2018-09-06 (I tried several last commits touching hash indexes, didn't dig deeper). Best regards, Alexander
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Thomas Munro <thomas.munro@gmail.com>
Дата:
On Sat, May 11, 2024 at 5:00 PM Alexander Lakhin wrote: > 11.05.2024 07:25, Thomas Munro wrote: > > On Sat, May 11, 2024 at 4:00 PM Alexander Lakhin wrote: > >> 11.05.2024 06:26, Thomas Munro wrote: > >>> Perhaps a no-image, no-change registered buffer should not be > >>> including an image, even for XLR_CHECK_CONSISTENCY? It's actually > >>> useless for consistency checking too I guess, this issue aside, > >>> because it doesn't change anything so there is nothing to check. > >> Yes, I think something wrong is here. I've reduced the reproducer to: > > Does it reproduce if you do this? > > > > - include_image = needs_backup || (info & > > XLR_CHECK_CONSISTENCY) != 0; > > + include_image = needs_backup || > > + ((info & XLR_CHECK_CONSISTENCY) != 0 && > > + (regbuf->flags & REGBUF_NO_CHANGE) == 0); > > No, it doesn't (at least with the latter, more targeted reproducer). OK so that seems like a candidate fix, but ... > > Unfortunately the back branches don't have that new flag from 00d7fb5e > > so, even if this is the right direction (not sure, I don't understand > > this clean registered buffer trick) then ... but wait, why are there > > are no failures like this in the back branches (yet at least)? Does > > your reproducer work for 16? I wonder if something relevant changed > > recently, like f56a9def. CC'ing Michael and Amit K for info. > > Maybe it's hard to hit (autovacuum needs to process the index page in a > narrow time frame), but locally I could reproduce the issue even on > ac27c74de(~1 too) from 2018-09-06 (I tried several last commits touching > hash indexes, didn't dig deeper). ... we'd need to figure out how to fix this in the back-branches too. One idea would be to back-patch REGBUF_NO_CHANGE, and another might be to deduce that case from other variables. Let me CC a couple more people from this thread, which most recently hacked on this stuff, to see if they have insights: https://www.postgresql.org/message-id/flat/d2c31606e6bb9b83a02ed4835d65191b38d4ba12.camel%40j-davis.com
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Jeff Davis <pgsql@j-davis.com>
Дата:
On Mon, 2024-05-13 at 11:15 +1200, Thomas Munro wrote: > > > > > Perhaps a no-image, no-change registered buffer should not be > > > > > including an image, even for XLR_CHECK_CONSISTENCY? It's > > > > > actually > > > > > useless for consistency checking too I guess, this issue > > > > > aside, > > > > > because it doesn't change anything so there is nothing to > > > > > check. I'm not convinced by that reasoning. Can't it check that nothing has changed? > > > > > > Does it reproduce if you do this? > > > > > > - include_image = needs_backup || (info & > > > XLR_CHECK_CONSISTENCY) != 0; > > > + include_image = needs_backup || > > > + ((info & XLR_CHECK_CONSISTENCY) != 0 && > > > + (regbuf->flags & REGBUF_NO_CHANGE) == > > > 0); > > > > No, it doesn't (at least with the latter, more targeted > > reproducer). > > OK so that seems like a candidate fix, but ... ... > ... we'd need to figure out how to fix this in the back-branches too. > One idea would be to back-patch REGBUF_NO_CHANGE, and another might > be > to deduce that case from other variables. Let me CC a couple more > people from this thread, which most recently hacked on this stuff, to > see if they have insights: Starting from the beginning, XLogRecordAssemble() calculates the CRC of the record (technically just the non-header portions, but that's not important here), including any backup blocks. Later, CopyXLogRecordToWAL() copies that data into the actual xlog buffers. If the data changes between those two steps, the CRC will be bad. For most callers, the contents are exclusive-locked, so there's no problem. For checksums, the data is copied out of shared memory into a stack variable first, so no concurrent activity can change it. For hash indexes, it tries to protect itself by passing REGBUF_NO_IMAGE. There are two problems: 1. That implies another invariant that we aren't checking for: that REGBUF_NO_CHANGE must be accompanied by REGBUF_NO_IMAGE. That doesn't seem to be true for all callers, see XLogRegisterBuffer(1, wbuf, wbuf_flags) in _hash_freeovflpage(). 2. As you point out, REGBUF_NO_IMAGE still allows an image to be taken if XLR_CHECK_CONSISTENCY is set, so we need to figure out what to do there. Can we take a step back and think harder about what hash indexes are doing and if there's a better way? Maybe hash indexes need to take a copy of the page, like in XLogSaveBufferForHint()? I'd prefer that we find a way to get rid of REGBUF_NO_CHANGE and make all callers follow the rules than to find new special cases that depend on REGBUF_NO_CHANGE. See these messages here: https://www.postgresql.org/message-id/b1f2d0f230d60fa8df33bb0b2af3236fde9d750d.camel%40j-davis.com https://www.postgresql.org/message-id/CA%2BTgmoY%2BdagCyrMKau7UQeQU6w4LuVEu%2ByjsmJBoXKAo6XbUUA%40mail.gmail.com In other words, we added REGBUF_NO_CHANGE for the call sites (only hash indexes) that don't follow the rules and where it wasn't easy to make them follow the rules. Now that we know of a concrete problem with the design, there's more upside to fixing it properly. Regards, Jeff Davis
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
On Thu, May 16, 2024 at 03:54:52PM -0700, Jeff Davis wrote: > On Mon, 2024-05-13 at 11:15 +1200, Thomas Munro wrote: >>>>>> Perhaps a no-image, no-change registered buffer should not be >>>>>> including an image, even for XLR_CHECK_CONSISTENCY? It's >>>>>> actually >>>>>> useless for consistency checking too I guess, this issue >>>>>> aside, >>>>>> because it doesn't change anything so there is nothing to >>>>>> check. > > I'm not convinced by that reasoning. Can't it check that nothing has > changed? That's something I've done four weeks ago in the hash replay code path, and having the image with XLR_CHECK_CONSISTENCY even if REGBUF_NO_CHANGE was necessary because replay was setting up a LSN on a REGBUF_NO_CHANGE page it should not have touched. > I'd prefer that we find a way to get rid of REGBUF_NO_CHANGE and make > all callers follow the rules than to find new special cases that depend > on REGBUF_NO_CHANGE. See these messages here: > > https://www.postgresql.org/message-id/b1f2d0f230d60fa8df33bb0b2af3236fde9d750d.camel%40j-davis.com > > https://www.postgresql.org/message-id/CA%2BTgmoY%2BdagCyrMKau7UQeQU6w4LuVEu%2ByjsmJBoXKAo6XbUUA%40mail.gmail.com > > In other words, we added REGBUF_NO_CHANGE for the call sites (only hash > indexes) that don't follow the rules and where it wasn't easy to make > them follow the rules. Now that we know of a concrete problem with the > design, there's more upside to fixing it properly. Yeah, agreed that getting rid of REGBUF_NO_CHANGE would be nice in the final picture. It still strikes me as a weird concept that WAL replay for hash indexes logs full pages just to be able to lock them at replay based on what's in the records. :/ -- Michael
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Jeff Davis <pgsql@j-davis.com>
Дата:
On Fri, 2024-05-17 at 10:12 +0900, Michael Paquier wrote: > That's something I've done four weeks ago in the hash replay code > path, and having the image with XLR_CHECK_CONSISTENCY even if > REGBUF_NO_CHANGE was necessary because replay was setting up a LSN on > a REGBUF_NO_CHANGE page it should not have touched. Then the candidate fix to selectively break XLR_CHECK_CONSISTENCY is not acceptable. > > Yeah, agreed that getting rid of REGBUF_NO_CHANGE would be nice in > the > final picture. It still strikes me as a weird concept that WAL > replay > for hash indexes logs full pages just to be able to lock them at > replay based on what's in the records. :/ I'm still not entirely clear on why hash indexes can't just follow the rules and exclusive lock the buffer and dirty it. Presumably performance would suffer, but I asked that question previously and didn't get an answer: https://www.postgresql.org/message-id/CA%2BTgmoY%2BdagCyrMKau7UQeQU6w4LuVEu%2ByjsmJBoXKAo6XbUUA%40mail.gmail.com And if that does affect performance, what about following the same protocol as XLogSaveBufferForHint()? Regards, Jeff Davis
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Robert Haas <robertmhaas@gmail.com>
Дата:
On Fri, May 17, 2024 at 10:56 AM Jeff Davis wrote:
> I'm still not entirely clear on why hash indexes can't just follow the
> rules and exclusive lock the buffer and dirty it. Presumably
> performance would suffer, but I asked that question previously and
> didn't get an answer:
>
> https://www.postgresql.org/message-id/CA%2BTgmoY%2BdagCyrMKau7UQeQU6w4LuVEu%2ByjsmJBoXKAo6XbUUA%40mail.gmail.com
In my defense, the last time I worked on hash indexes was 7 years ago.
If this question had come up within a year or two of that work, I
probably would have both (a) had a much clearer idea of what the
answer was and (b) felt obliged to drop everything and go research it
if I didn't. But at this point, I feel like it's fair for me to tell
you what I know and leave it to you to do further research if you feel
like that's warranted. I know that we're each responsible for what we
commit, but I don't really think that should extend to having to
prioritize answering a hypothetical question ("what would happen if X
thing worked like Y instead of the way it does?") about an area I
haven't touched in long enough for every release that doesn't contain
those commits to be out of support. If you feel otherwise, let's have
that argument, but I have a feeling that it may be more that you're
hoping I have some kind of oracular powers which, in reality, I lack.
--
Robert Haas
EDB: http://www.enterprisedb.com
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
On Fri, 17 May 2024 07:56:23 -0700, Jeff Davis wrote:
> On Fri, 2024-05-17 at 10:12 +0900, Michael Paquier wrote:
> > That's something I've done four weeks ago in the hash replay code
> > path, and having the image with XLR_CHECK_CONSISTENCY even if
> > REGBUF_NO_CHANGE was necessary because replay was setting up a LSN on
> > a REGBUF_NO_CHANGE page it should not have touched.
>
> Then the candidate fix to selectively break XLR_CHECK_CONSISTENCY is
> not acceptable.
>
> >
> > Yeah, agreed that getting rid of REGBUF_NO_CHANGE would be nice in
> > the
> > final picture. It still strikes me as a weird concept that WAL
> > replay
> > for hash indexes logs full pages just to be able to lock them at
> > replay based on what's in the records. :/
>
> I'm still not entirely clear on why hash indexes can't just follow the
> rules and exclusive lock the buffer and dirty it. Presumably
> performance would suffer, but I asked that question previously and
> didn't get an answer:
>
> https://www.postgresql.org/message-id/CA%2BTgmoY%2BdagCyrMKau7UQeQU6w4LuVEu%2ByjsmJBoXKAo6XbUUA%40mail.gmail.com
>
> And if that does affect performance, what about following the same
> protocol as XLogSaveBufferForHint()?
>
> Regards,
> Jeff Davis
Hi,
Reviving this thread because I hit the same CRC failure on current
master while testing something else.
Recap of the bug:
hashbucketcleanup(), _hash_freeovflpage() and _hash_squeezebucket()
register the primary bucket page with REGBUF_STANDARD | REGBUF_NO_IMAGE
| REGBUF_NO_CHANGE, holding only a pin on it, purely to force a cleanup
lock during replay. With wal_consistency_checking covering the hash RM,
XLogRecordAssemble() takes a full-page image of that block anyway:
include_image = needs_backup || (info & XLR_CHECK_CONSISTENCY) != 0;
The CRC is then computed over a page another backend is free to modify
(it holds only a pin), and before CopyXLogRecordToWAL() runs the page
changes, so the record lands with a bad CRC. On a standby that is a
fatal "incorrect resource manager data checksum in record".
AFAICT, 2 things kept this open last time:
1. Thomas's narrow fix (skip the image for REGBUF_NO_CHANGE) was ruled
out because Michael's f56a9def seemed to rely on an image being present
for a REGBUF_NO_CHANGE page. Looking again, f56a9def is on the squeeze
*redo* path: it stops replay from setting an LSN on the write buffer
(block 1) when that buffer turns out not to be modified. That redo code
reads only the per-buffer data registered with XLogRegisterBufData() and
the xl_hash_squeeze_page fields, never a full-page image, so suppressing
the image does not affect it. The block that triggers the CRC failure
is a different one: the primary bucket page registered as block 0 only
to take a cleanup lock, which is never image-applied at replay.
Suppressing its image is safe.
2. Jeff asked why hash can't just follow the rules and exclusive-lock +
dirty the buffer. That is the better long-term answer, but it is a
non-trivial rework of the hash cleanup/squeeze locking and does not
back-patch cleanly. The attached fix is the minimal, back-patchable
change and does not foreclose the rework.
Proposed fix:
Never take a full-page image for a REGBUF_NO_CHANGE buffer, even under
XLR_CHECK_CONSISTENCY.
The reasoning is the same one Thomas gave: there is nothing to
consistency-check on a block the record does not change, and the page is
not safe to read while assembling the record.
verifyBackupPageConsistency() is taught to skip a registered block that
carries no image, rather than asserting one is present (that assertion
is what fires first on an assert build with the fix in place).
This keeps REGBUF_NO_CHANGE as the single, documented marker for "pinned
but not content-locked, not modified here" and makes its
consistency-check behaviour match its contract.
Testing:
I reproduced the failure with a primary plus a streaming standby,
wal_consistency_checking='hash', and eight sessions doing:
INSERT INTO h SELECT 1 FROM generate_series(1,400);
DELETE FROM h WHERE ctid IN (SELECT ctid FROM h LIMIT 150);
against a single-bucket hash index, with aggressive autovacuum. On
unpatched master the standby dies with the CRC error within a few
seconds, every run. With the patch, runs replayed clean and the standby
caught up each time.
This still reproduces on all supported back branches (Alexander saw it
as far back as 2018); REGBUF_NO_CHANGE exists only since 00d7fb5e (v17),
so the back-patch needs the equivalent condition expressed without the
flag. I can prepare those once the master approach has agreement.
best.
-greg
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
On Fri, Oct 23, 2026 at 10:48:44AM +0000, Greg Burd wrote:
> Reviving this thread because I hit the same CRC failure on current
> master while testing something else.
Eh, and I thought that we were entirely done here. Nice
investigation.
> 1. Thomas's narrow fix (skip the image for REGBUF_NO_CHANGE) was ruled
> out because Michael's f56a9def seemed to rely on an image being present
> for a REGBUF_NO_CHANGE page. Looking again, f56a9def is on the squeeze
> *redo* path: it stops replay from setting an LSN on the write buffer
> (block 1) when that buffer turns out not to be modified. That redo code
> reads only the per-buffer data registered with XLogRegisterBufData() and
> the xl_hash_squeeze_page fields, never a full-page image, so suppressing
> the image does not affect it. The block that triggers the CRC failure
> is a different one: the primary bucket page registered as block 0 only
> to take a cleanup lock, which is never image-applied at replay.
> Suppressing its image is safe.
>
> 2. Jeff asked why hash can't just follow the rules and exclusive-lock +
> dirty the buffer. That is the better long-term answer, but it is a
> non-trivial rework of the hash cleanup/squeeze locking and does not
> back-patch cleanly. The attached fix is the minimal, back-patchable
> change and does not foreclose the rework.
I'm still wondering if this would not be the best thing long-term.
Perhaps not, so [shrug].
> Never take a full-page image for a REGBUF_NO_CHANGE buffer, even under
> XLR_CHECK_CONSISTENCY.
>
> The reasoning is the same one Thomas gave: there is nothing to
> consistency-check on a block the record does not change, and the page is
> not safe to read while assembling the record.
> verifyBackupPageConsistency() is taught to skip a registered block that
> carries no image, rather than asserting one is present (that assertion
> is what fires first on an assert build with the fix in place).
>
> This keeps REGBUF_NO_CHANGE as the single, documented marker for "pinned
> but not content-locked, not modified here" and makes its
> consistency-check behaviour match its contract.
Hmm, okay, I am fine with simpler for the sake of this proposition.
I'm finding the comments a bit over-complicated, so I've adjusted
these as of the attached. What do you think?
> I reproduced the failure with a primary plus a streaming standby,
> wal_consistency_checking='hash', and eight sessions doing:
>
> INSERT INTO h SELECT 1 FROM generate_series(1,400);
> DELETE FROM h WHERE ctid IN (SELECT ctid FROM h LIMIT 150);
>
> against a single-bucket hash index, with aggressive autovacuum. On
> unpatched master the standby dies with the CRC error within a few
> seconds, every run. With the patch, runs replayed clean and the standby
> caught up each time.
Ah, thanks for that. I also got a reproduction with these conditions.
> This still reproduces on all supported back branches (Alexander saw it
> as far back as 2018); REGBUF_NO_CHANGE exists only since 00d7fb5e (v17),
> so the back-patch needs the equivalent condition expressed without the
> flag. I can prepare those once the master approach has agreement.
Honestly, I am not convinced that it is worth bothering with the
v14~16 branches: REGBUF_NO_CHANGE does not exist there, and we would
need to identify a way to identify pin-only buffers, probably with an
exclusive lock check when a record is assembled, or something like
that. I really cannot get excited by that just for the sake of making
wal_consistency_checking able to work better for hash records there.
So let's leave it at v17~ where the regbuf flag exists.
@@ -2479,7 +2479,13 @@ verifyBackupPageConsistency(XLogReaderState *record)
continue;
}
- Assert(XLogRecHasBlockImage(record, block_id));
+ /*
+ * A block registered with REGBUF_NO_CHANGE is not modified by this
+ * record and carries no full-page image (see XLogRecordAssemble), so
+ * there is nothing to consistency-check for it. Skip it.
+ */
+ if (!XLogRecHasBlockImage(record, block_id))
+ continue;
This suggestion makes WAL replay weaker in the detection of a failure
mode attached to the record getting assembled. As this is linked to
only one specific condition in XLogRecordAssemble(), and you're
marking that in a comment, that would be hard to miss. I'm OK with
this suggestion. It's not like we should add a new marker in the
records for these purpose, the WAL bits are too precious for that.
What do you think about the comments I've touched?
--
Michael
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On 2026-10-26 12:17:55 +0900, Michael Paquier wrote: > > 2. Jeff asked why hash can't just follow the rules and exclusive-lock + > > dirty the buffer. That is the better long-term answer, but it is a > > non-trivial rework of the hash cleanup/squeeze locking and does not > > back-patch cleanly. The attached fix is the minimal, back-patchable > > change and does not foreclose the rework. > > I'm still wondering if this would not be the best thing long-term. > Perhaps not, so [shrug]. I frankly think it's pretty much unacceptable for a niche index like hash to violate the rules like that. If it were btree, it'd perhaps be worthwhile to add generic infrastructure for this, but here it doesn't seem like the juice is worth the squeeze. > As of this commit, never take an image for a REGBUF_NO_CHANGE buffer, even > under XLR_CHECK_CONSISTENCY. There is no need to do a consistency check on > a block not changed by a record. verifyBackupPageConsistency() is taught to > skip a registered block that carries no image rather than asserting one > should be present. I'm not really convinced by that argument. It's probably the best answer in the back branches, but I think we shouldn't do this in master. Greetings, Andres Freund
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Greg Burd <greg@burd.me>
Дата:
On 2026-10-26 Michael Paquier wrote:
> I'm finding the comments a bit over-complicated, so I've adjusted
> these as of the attached. What do you think?
Hey Michael,
First, thanks for taking a look so fast and for offering a solid review
and revision of the patch I proposed. I'll use your wording, it is far
better than mine. The one thing I'd keep from the longer version is a
pointer from verifyBackupPageConsistency() to the exact line in
XLogRecordAssemble() that decides to omit the image, since the two have
to stay in agreement and they're far apart in the file. A half-line is
enough:
/* no image was taken (REGBUF_NO_CHANGE in XLogRecordAssemble); skip */
> So let's leave it at v17~ where the regbuf flag exists.
Agreed, drop v14-16. I'd floated the back-branch version, but the only thing
it buys there is making wal_consistency_checking='hash' not crash a standby,
and on reflection that's not worth inventing a pin-only detection path those
branches don't otherwise need.
On 2026-10-26 Andres Freund wrote:
> I frankly think it's pretty much unacceptable for a niche index like hash
> to violate the rules like that.
> [...]
> It's probably the best answer in the back branches, but I think we
> shouldn't do this in master.
Hey Andres,
Thanks for taking the time to review, I'm curious why you used the term
"niche" with hash indexes. Not related to this topic, just an aside.
You're right, the real problem is hash CRCs a page it holds only a pin on, so
another backend can change it under the record. The clean fix is to make the
three call sites (hashbucketcleanup, _hash_freeovflpage, _hash_squeezebucket)
stop reading a page they don't content-lock and either take the buffer the
normal way, or follow the XLogSaveBufferForHint() protocol Jeff pointed at.
Where I'd push back is on making that the gate for master while the standby
crash stays unfixed. Two things make me want the small fix in master too, not
only the back branches:
1. REGBUF_NO_CHANGE's contract already is "pinned, not content-locked, not
modified here". Taking a full-page image of such a block under
XLR_CHECK_CONSISTENCY contradicts that contract on its own terms:
there's nothing to consistency-check on a block the record doesn't
change, and the page isn't safe to read while assembling the record.
So skipping the image isn't only a hash workaround it makes the
consistency-check path honor the flag's definition. Any future code
that legitimately registers a pin-only block hits the same assertion
today.
2. If master keeps taking the image and the hash rework lands later, the
rework has to touch the same three sites anyway, and in the meantime
master is the one branch where wal_consistency_checking='hash' faults.
Fixing the flag's behaviour in master and doing the hash rework as a
follow-up are not in tension, the rework doesn't depend on the image
still being taken.
Concretely, here's what I propose:
- master and v17+: the minimal fix (skip the image for REGBUF_NO_CHANGE,
with Michael's comments). This stops the standby crash on every branch
that has the flag and makes the consistency check match the contract.
- master, separate patch: make hash stop modifying pin-only buffers at the
three sites, so hash follows the buffer rules and the REGBUF_NO_CHANGE |
REGBUF_NO_IMAGE dance for "just force a cleanup lock" is no longer
needed. I'm willing to write this; it's the non-trivial part, and I'd
rather it be reviewed on its own than bundled with the crash fix.
If you'd still rather master not carry the flag-level fix at all and wait for
the hash rework, I can live with that but then I'd want the rework to be the
thing we track for master now, not a someday item, because the crash is live on
master today. Which of those do you prefer?
I'll hold the back-branch patches and post a v-next of the master patch with
Michael's comments once we've settled master-only-rework vs
flag-fix-plus-rework.
best,
-greg
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Andres Freund <andres@anarazel.de>
Дата:
Hi, On October 26, 2026 10:33:16 AM EDT, Greg Burd wrote: >On 2026-10-26 Andres Freund wrote: >> I frankly think it's pretty much unacceptable for a niche index like hash >> to violate the rules like that. >> [...] >> It's probably the best answer in the back branches, but I think we >> shouldn't do this in master. > >Thanks for taking the time to review, I'm curious why you used the term >"niche" with hash indexes. Not related to this topic, just an aside. I think they're almost unused and don't offer enough advantage over btree (and perform catastrophically bad in many cases). Instead of making them WAL logged a few years back; we should have just ripped them out. The advantage hash does have, i.e. large key handling, would have better been addressed by adding support to transparently btree indexing a hash of the key + recheck. Greetings, Andres -- Sent from my phone. Please excuse my brevity.
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Greg Burd <greg@burd.me>
Дата:
On 2026-10-26 Andres Freund wrote: > I think they're almost unused and don't offer enough advantage over btree > (and perform catastrophically bad in many cases). Instead of making them WAL > logged a few years back; we should have just ripped them out. Fair, whether hash earns its place is a bigger conversation than this bug. I'll just note one data point from the other thread I have open: a good part of the "catastrophically bad in many cases" is the metapage tuple counter serialising every insert on one buffer, and that looks removable. Inserts stop touching the metapage on the common path and hash then scales like btree on a concurrent insert workload in my measurements. That doesn't change your conclusion about large-key handling, but it does move some of the "performs badly" into "performed badly". > The advantage hash does have, i.e. large key handling, would have better been > addressed by adding support to transparently btree indexing a hash of the key > + recheck. No disagreement that that would have been the better design. It's not where we are, though, and ripping out a shipped, WAL-logged, user-visible AM is its own multi-release project. Which leaves the thing this thread actually needs a decision on, independent of hash's long-term fate: master faults a standby under wal_consistency_checking='hash' today. The one-line fix (skip the full-page image for a REGBUF_NO_CHANGE block, which contradicts the flag's own contract to take) stops that and Michael's OK with it for v17+. You'd said you'd rather master wait for the proper hash rework. I'm fine either way, but if master isn't getting the flag-level fix now, I'd like the rework to be the tracked item for master rather than a someday, the crash is live on master. So: flag fix in master now plus rework as follow-up, or rework-only for master? I'll build whichever, I just don't want it to stall into neither. best, -greg
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Andres and Greg,
> I think they're almost unused and don't offer enough advantage over btree
I largely agree with this. In my experience, B-tree accounts for 95%+ of
indexes, and all other access methods combined make up only a
small fraction. But I do see quite a few hash index users.
> we should have just ripped them out.
I have mixed feelings on this. On one hand, hash is probably the least used
"general-purpose" index since its use case overlaps directly with B-tree,
whereas GiST, SP-GiST, and BRIN exist for specialized data types or access
patterns that B-tree can't handle. On the other hand, in practice I still see
hash indexes used at least as often as GiST, BRIN, or SP-GiST.
I suspect part of the low adoption is historical baggage from being
unlogged prior to old version, which gave hash indexes a bad reputation in the
community, it also miss some features for general OLTP workloads
> I think they're almost unused and don't offer enough advantage over btree
I largely agree with this. In my experience, B-tree accounts for 95%+ of
indexes, and all other access methods combined make up only a
small fraction. But I do see quite a few hash index users.
> we should have just ripped them out.
I have mixed feelings on this. On one hand, hash is probably the least used
"general-purpose" index since its use case overlaps directly with B-tree,
whereas GiST, SP-GiST, and BRIN exist for specialized data types or access
patterns that B-tree can't handle. On the other hand, in practice I still see
hash indexes used at least as often as GiST, BRIN, or SP-GiST.
I suspect part of the low adoption is historical baggage from being
unlogged prior to old version, which gave hash indexes a bad reputation in the
community, it also miss some features for general OLTP workloads
I feel there is plenty of room for improvement there.
> The advantage hash does have, i.e. large key handling, would have better been
> addressed by adding support to transparently btree indexing a hash of the key + recheck.
That's an interesting point. But I think users can do that today with expression
> The advantage hash does have, i.e. large key handling, would have better been
> addressed by adding support to transparently btree indexing a hash of the key + recheck.
That's an interesting point. But I think users can do that today with expression
index right?
Thanks,
Shihao
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
On Mon, Oct 26, 2026 at 09:46:18AM -0400, Andres Freund wrote: > I frankly think it's pretty much unacceptable for a niche index like hash to > violate the rules like that. If it were btree, it'd perhaps be worthwhile to > add generic infrastructure for this, but here it doesn't seem like the juice > is worth the squeeze. I'm definitely not convinced that hash is a sufficient argument for having more infrastructure. What this is telling us here is the contrary: we should have less infrastructure. So I'd love to be able to put REGBUF_NO_CHANGE in the garbage bin and have an assert in the replay code instead of silently ignoring a case. > I'm not really convinced by that argument. It's probably the best answer in > the back branches, but I think we shouldn't do this in master. I'm not sure that I can side with your argument here. Doing nothing on master means that we're still open to the CRC problem until we decide to fix hash, so it still looks like a problem that needs to be tackled in three steps: - Avoid the CRC problem down to v17, including HEAD. - Address hash to avoid the rule breakage. - Lift the check in replay for wal_consistency_checking (re-add the assert) and push REGBUF_NO_CHANGE into orbit. There is nothing more permanent than a temporary fix, as some say, but I'd like to trust in something happening for hash. I'm not planning to code that myself, though, but if somebody is willing to work that, be it with an LLM, I would read the code. That's just to say that I don't see a downside with including HEAD in step 1. -- Michael
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Greg Burd <greg@burd.me>
Дата:
On Mon, 26 Oct 2026 14:08:29 -0400, shihao zhong wrote: > Hi Andres and Greg, > > > I think they're almost unused and don't offer enough advantage over btree > > I largely agree with this. In my experience, B-tree accounts for 95%+ of > indexes, and all other access methods combined make up only a > small fraction. But I do see quite a few hash index users. While I agree that the vast majority of users rightly default to the BTREE index I don't find that a compelling reason to drop HASH. I see that as a challenge, maybe HASH isn't used because it is not as well maintained as BTREE and needs some attention [0]? > > we should have just ripped them out. > > I have mixed feelings on this. I think this would invite further specialization of code outside nbtree into shapes that only support nbtree reducing the ability to innovate with other table and index AMs. Sure there is GIN, GiST, BRIN, etc. but IMO hash represents a quadrant of access patterns that we should support, and our code there today isn't inspiring many to give it a look even for use cases that fit that pattern well. That's a signal to innovate, not remove code. We have this issue today with HEAP, because we only have one table AM in core things are simpler to maintain but it is also easier for heap-isms to leak outside the table AM boundaries in the name of performance or other goals. IMO this is a long-term philosophical question for Postgres; is it extensible or is it highly opinionated and specialized? > On one hand, hash is probably the least used > "general-purpose" index since its use case overlaps directly with B-tree, > whereas GiST, SP-GiST, and BRIN exist for specialized data types or access > patterns that B-tree can't handle. On the other hand, in practice I still > see hash indexes used at least as often as GiST, BRIN, or SP-GiST. > > I suspect part of the low adoption is historical baggage from being > unlogged prior to old version, which gave hash indexes a bad reputation in > the community, it also miss some features for general OLTP workloads > > I feel there is plenty of room for improvement there. I agree that there is historical baggage, performance, and possibly simple knowledge gaps that push the adoption toward BTREE. > > The advantage hash does have, i.e. large key handling, would have better > > been addressed by adding support to transparently btree indexing a hash > > of the key + recheck. > > That's an interesting point. But I think users can do that today with > expression index right? Expression indexes prevent HOT updates, so maybe you could but at what cost? > Thanks, > Shihao best. -greg
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
On Tue, 27 Oct 2026 08:06:48 +0900, Michael Paquier wrote:
> it still looks like a problem that needs to be tackled in three steps:
> - Avoid the CRC problem down to v17, including HEAD.
> - Address hash to avoid the rule breakage.
> - Lift the check in replay for wal_consistency_checking (re-add the
> assert) and push REGBUF_NO_CHANGE into orbit.
> [...] if somebody is willing to work that, be it with an LLM, I would
> read the code.
That plan works for me, and I'll take the hash rework (step 2).
Step 1 (down to v17, including HEAD): the flag-level fix we discussed,
with your comment wording. I'll post it as the next version shortly.
The one line I'd keep is the pointer from verifyBackupPageConsistency()
back to XLogRecordAssemble(), since the two have to stay in agreement
and they're far apart in the file.
Step 2 (make hash stop breaking the rule): the three sites that register
a pin-only primary/bucket page purely to force a replay cleanup lock
(hashbucketcleanup, _hash_freeovflpage, _hash_squeezebucket). The
tricky part isn't locking the page, it's doing so without losing the
replay-cleanup-lock behaviour the registration exists to produce, so the
standby still serialises against scans the same way. The
XLogSaveBufferForHint() protocol Jeff pointed at in 2024 is the model
I'll start from -- it already copes with WAL-logging a page that isn't
held exclusively. I'll post that on this thread for review before
worrying about step 3; once it's in, step 3 (re-add the assert, remove
REGBUF_NO_CHANGE) falls out.
> There is nothing more permanent than a temporary fix [...] but I'd like
> to trust in something happening for hash.
Too true!
On 2026-10-26 shihao zhong wrote:
> [btree indexing a hash of the key + recheck] users can do that today with
> expression index right?
Something else occured to me on this, the gap is the interesting bit.
You can do:
CREATE INDEX ON t (hashtext(col)) and then query
WHERE hashtext(col) = hashtext('x') AND col = 'x'
but you have to write the hash and the recheck yourself in every query,
and the planner won't use that index for a plain col = 'x'.
What Andres described is the planner doing that transparently for col =
'x' against a normal-looking index, which the expression-index approach
doesn't give you, and HOT is out of the question [0]. So it's a manual
workaround today, not the transparent feature. (Orthogonal to this
thread; just answering.)
best,
-greg
[0] https://postgr.es/m/78574B24-BE0A-42C5-8075-3FA9FA63B8FC@amazon.com
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Greg,
> That's a signal to innovate, not remove code.
I agree with that and I would like to spend some time to modernize hash,
I will start looking after the PG19 release and happy to review any of your
hash changes.
> Expression indexes prevent HOT updates, so maybe you could but at what
> cost?
> cost?
Haven't really tested that, just some wild thinking, but I think hash index also
have similar limitations.
Thanks,
Shihao
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Greg Burd <greg@burd.me>
Дата:
On Tuesday, October 27th, 2026 at 10:05 AM, shihao zhong wrote: > Hi Greg, > > That's a signal to innovate, not remove code. > > I agree with that and I would like to spend some time to modernize hash, > I will start looking after the PG19 release and happy to review any of your > hash changes. Sounds like a plan to me. > > Expression indexes prevent HOT updates, so maybe you could but at what > > cost? > > Haven't really tested that, just some wild thinking, but I think hash index also > have similar limitations. This is a heap limitation, and update to a row where there is an expression index that has a column reference which was modified prevents the HOT update even if that expression didn't result in a material change to the index key. > Thanks, > Shihao -greg
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
Here is step 2, the hash rework. 0002 is the step 3 end state, marked
NOT FOR MERGE, so you can see where this lands.
0001: Don't register pin-only primary bucket pages in hash WAL records
XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
XLOG_HASH_SQUEEZE_PAGE register the primary bucket page only so that
redo takes a cleanup lock on it. Redo never reads data for that block.
0001 puts the block number in the record's main data instead (a new
bucket_blkno field), and redo reads the block and calls
LockBufferForCleanup() on it directly, at the same point and in the same
order as today. The page is registered only when the record changes it.
For SQUEEZE_PAGE that also covers the REGBUF_NO_CHANGE registration of
the write page (the case where the primary page is the write page but
nothing moved onto it): block 1 is now registered only when it is
modified. After this, hash registers only buffers it holds exclusively
locked and dirty.
Reading an unregistered block in redo has precedent: nbtree's "pin scan"
did exactly that (XLogReadBufferExtended + LockBufferForCleanup) until
9f83468b353, which removed it because it was no longer needed, not
because it was unsafe ACAICT. The cost is that recovery prefetch no
longer sees the bucket page for these records. The record format
changes, so XLOG_PAGE_MAGIC is bumped; master only.
Why not lock the bucket page on the primary, as Jeff asked in 2024? I
asked for an exhaustive search.
It deadlocks if you take the lock where the buffer is registered. In
_hash_freeovflpage() that point is after the metapage is locked
exclusive. A scan of a bucket that an incomplete split is still
populating 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 nothing detects the cycle and cancel doesn't break it. I reproduced
it deterministically with an injection point (3 runs out of 3):
pg_cancel_backend() on the VACUUM does nothing, and every insert into
the index queues behind the metapage. Taking the bucket lock before the
metapage is read avoids it, and that placement passed the same test (3
of 3). 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. The approach taken in 0001 has neither cost and
takes no new lock on the primary.
I read the code and that analysis seems on target to me.
0002 [NOT FOR MERGE]: Remove REGBUF_NO_CHANGE
With 0001 there are no users left, so XLogRegisterBuffer() asserts
unconditionally that every buffer is locked and dirty. On a tree with
the step 1 patch, step 3 would also restore the
Assert(XLogRecHasBlockImage()) in verifyBackupPageConsistency() and drop
the XLogRecordAssemble() special case. On master neither exists yet.
Testing (16-vCPU Debian, cassert builds):
A = master, B = master + step 1, C = master + 0001, D = C + 0002
- CRC reproduction: primary + streaming standby,
wal_consistency_checking = 'hash', 8 sessions inserting and deleting
on a single-bucket index, aggressive autovacuum.
A: the standby stopped on "incorrect resource manager data checksum"
in all runs, as expected (control case).
B, C, D: the standby caught up with no errors, 3 of 3 each.
C and D don't have step 1, and D has neither step 1 nor the
REGBUF_NO_CHANGE escape in XLogRegisterBuffer(), with the replay
assert in verifyBackupPageConsistency() still in place.
So 0001 removes the need for the flag; it doesn't rely on step 1 to
hide the problem.
- Replay correctness: a separate run per build, with and without
wal_consistency_checking, mixing insert/rollback churn, vacuum,
rewrites of a stable row set, and four hot standby readers counting
that set through the index. Each run produced thousands of
DELETE/MOVE/SQUEEZE records with the bucket page not modified.
C and D passed both ways: no bad reads, matching counts on primary and
standby, and matching live-item counts on every bucket and overflow
page.
- Cleanup lock on the standby: a cursor on the standby is parked inside
the bucket's overflow chain, then the primary vacuums so that the
records are 9 DELETE, 4 MOVE_PAGE_CONTENTS and 4 SQUEEZE_PAGE, all
with is_primary F.
On A, C and D, replay waits on BufferCleanup until the cursor
finishes, and the cursor sees all 2250 rows.
As a control, a build of C with the cleanup lock swapped for a plain
exclusive lock lets replay run under the scan, and the cursor only
sees 1686.
- meson test regress, isolation, pg_waldump and the hash module, plus
recovery/027_stream_regress with
PG_TEST_EXTRA=wal_consistency_checking: all pass on C and D.
Of note for reviewers because this does break WAL convention, so it
deserves a bit more scrutiny.
With 0001, redo reads a block that the record does not register. It
takes the relation from a block that is always registered (block 1 for
DELETE and MOVE_PAGE_CONTENTS, block 2 for SQUEEZE_PAGE). It 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 isn't
modified, so it needs no full-page image and no LSN update. 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 already in shared buffers. The other is tools that
collect changed blocks from WAL, such as pg_rewind and the WAL
summarizer. They used to count the bucket page as changed for these
records even though it never was, so dropping it is a fix, not a loss.
The supporting AI-generated scripts are small, attached as
scripts.tgz.nocfbot.
This fix is referenced by another thread working on hash performance
issues as required [0].
best.
-greg
[0] https://postgr.es/m/auHfGQ-MN1Oij_dc@floki
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
On Tue, 27 Oct 2026 at 19:25, Greg Burd wrote: > > On Tue, 27 Oct 2026 08:06:48 +0900, Michael Paquier wrote: > > it still looks like a problem that needs to be tackled in three steps: > > - Avoid the CRC problem down to v17, including HEAD. > > - Address hash to avoid the rule breakage. > > - Lift the check in replay for wal_consistency_checking (re-add the > > assert) and push REGBUF_NO_CHANGE into orbit. > > [...] if somebody is willing to work that, be it with an LLM, I would > > read the code. > > That plan works for me, and I'll take the hash rework (step 2). > > Step 1 (down to v17, including HEAD): the flag-level fix we discussed, > with your comment wording. I'll post it as the next version shortly. > The one line I'd keep is the pointer from verifyBackupPageConsistency() > back to XLogRecordAssemble(), since the two have to stay in agreement > and they're far apart in the file. Thanks for working on this. These comments are on the step 1 patch (v1-0001, "Don't take a full-page image for REGBUF_NO_CHANGE buffers"). I could reproduce the problem consistently with a VACUUM on a table with a hash index and a concurrent INSERT, with wal_consistency_checking = 'hash'. The test is attached; it needs a test-only injection point after the CRC loop in XLogRecordAssemble(). Your step 1 patch fixes it. Few comments: 1. The README, the macro comment, the code comment and the commit message say such a buffer "never has a full-page image taken". The code is include_image = needs_backup, so an image is still taken when needs_backup is true. For example, _hash_freeovflpage() registers the write buffer with REGBUF_STANDARD | REGBUF_NO_CHANGE, without REGBUF_NO_IMAGE, when the primary bucket page is the write page and no tuples are moved onto it. After a checkpoint, that record carries an ordinary FPI of the page. + The REGBUF_NO_CHANGE flag indicates that the buffer is registered without + being modified by this record, and possibly without an exclusive content + lock (for example, to force a cleanup lock on the block during replay). + Such a buffer never has a full-page image taken, not even when WAL + consistency checking is enabled: its contents may change concurrently Is this ok, or should we mention like "no consistency-check image" 2. The patch does not apply to REL_17 (the README hunk fails), so a separate patch is needed for that branch. Regards, Vignesh
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Andres Freund <andres@anarazel.de>
Дата:
On 2026-10-27 08:06:48 +0900, Michael Paquier wrote: > On Mon, Oct 26, 2026 at 09:46:18AM -0400, Andres Freund wrote: > > I frankly think it's pretty much unacceptable for a niche index like hash to > > violate the rules like that. If it were btree, it'd perhaps be worthwhile to > > add generic infrastructure for this, but here it doesn't seem like the juice > > is worth the squeeze. > > I'm definitely not convinced that hash is a sufficient argument for > having more infrastructure. What this is telling us here is the > contrary: we should have less infrastructure. So I'd love to be able > to put REGBUF_NO_CHANGE in the garbage bin and have an assert in the > replay code instead of silently ignoring a case. Agreed. > > I'm not really convinced by that argument. It's probably the best answer in > > the back branches, but I think we shouldn't do this in master. > > I'm not sure that I can side with your argument here. Doing nothing > on master means that we're still open to the CRC problem until we > decide to fix hash, so it still looks like a problem that needs to be > tackled in three steps: > - Avoid the CRC problem down to v17, including HEAD. > - Address hash to avoid the rule breakage. > - Lift the check in replay for wal_consistency_checking (re-add the > assert) and push REGBUF_NO_CHANGE into orbit. Fair enough. I guess I'd hoped that one of the folks involved in adding the hash index WAL logging would chime in and fix this properly. > There is nothing more permanent than a temporary fix, as some say, > but I'd like to trust in something happening for hash. I guess I don't have that trust in this case. This IIRC isn't the first complaint about the odd locking stuff that hash has. Ceterum censeo index access/hash esse delendum. Greetings, Andres Freund
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
On Wed, Oct 28, 2026 at 11:57:53AM -0400, Andres Freund wrote: > Fair enough. I guess I'd hoped that one of the folks involved in adding the > hash index WAL logging would chime in and fix this properly. If input does not show up, I see nothing to do here except somebody else popping up to take responsibility for the change. Actually, I may not mind, this stuff is annoying.. Applied the workaround down to v17 for now. > Ceterum censeo index access/hash esse delendum. I doubt we would be able to do that, if ever. -- Michael
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
On Wed, Oct 28, 2026 at 01:29:39PM +0000, Greg Burd wrote: > - CRC reproduction: primary + streaming standby, > wal_consistency_checking = 'hash', 8 sessions inserting and deleting > on a single-bucket index, aggressive autovacuum. > > A: the standby stopped on "incorrect resource manager data checksum" > in all runs, as expected (control case). > > B, C, D: the standby caught up with no errors, 3 of 3 each. That sounds encouraging, as a start. 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. You could also add me in CC if you wish. As far as I recall, we rely on the registered buffer at replay to lift a bit the lock restrictions for concurrency purposes, but that's pretty specialized in itself. Thanks, -- Michael
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Amit Kapila <amit.kapila16@gmail.com>
Дата:
On Wed, Oct 28, 2026 at 6:59 PM Greg Burd wrote:
>
> Here is step 2, the hash rework. 0002 is the step 3 end state, marked
> NOT FOR MERGE, so you can see where this lands.
>
> 0001: Don't register pin-only primary bucket pages in hash WAL records
>
> XLOG_HASH_DELETE, XLOG_HASH_MOVE_PAGE_CONTENTS and
> XLOG_HASH_SQUEEZE_PAGE register the primary bucket page only so that
> redo takes a cleanup lock on it. Redo never reads data for that block.
>
> 0001 puts the block number in the record's main data instead (a new
> bucket_blkno field), and redo reads the block and calls
> LockBufferForCleanup() on it directly, at the same point and in the same
> order as today. The page is registered only when the record changes it.
>
> For SQUEEZE_PAGE that also covers the REGBUF_NO_CHANGE registration of
> the write page (the case where the primary page is the write page but
> nothing moved onto it): block 1 is now registered only when it is
> modified. After this, hash registers only buffers it holds exclusively
> locked and dirty.
>
> Reading an unregistered block in redo has precedent: nbtree's "pin scan"
> did exactly that (XLogReadBufferExtended + LockBufferForCleanup) until
> 9f83468b353, which removed it because it was no longer needed, not
> because it was unsafe ACAICT. The cost is that recovery prefetch no
> longer sees the bucket page for these records. The record format
> changes, so XLOG_PAGE_MAGIC is bumped; master only.
>
This approach looks reasonable to me.
*
@@ -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;
Though harmless, we don't need this for primary bucket pages, so one
idea could be to use XLogRegisterData to register this block number
for overflow pages only. This would save four bytes for the cases
where we don't perform the cleanup operations on overflow pages, the
same would be true for other cases.
--
With Regards,
Amit Kapila.
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Jeff Davis <pgsql@j-davis.com>
Дата:
On Tue, 2026-10-27 at 10:04 -0400, shihao zhong wrote: > I agree with that and I would like to spend some time to > modernize hash, There have been prior efforts in this area, such as WAL logging, under the same assumption: that people don't use hash indexes, but would if we put more work into them. At this point, the bar is quite high for convincing people to use them. Being slightly better in some cases is probably not enough to get attention. As Andres said, the long keys problem with btrees is incidental, and can be solved other ways. Also, btree indexes aren't standing still, which makes it even harder to make the case. Regards, Jeff Davis
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Jeff Davis <pgsql@j-davis.com>
Дата:
On Mon, 2026-10-26 at 11:15 -0400, Andres Freund wrote: > The advantage hash does have, i.e. large key handling, would have > better been addressed by adding support to transparently btree > indexing a hash of the key + recheck. In theory we could generalize this. We can take any predicate x=a, create a new implied predicate f(x)=f(a), and then use a functional index on f(x). (Assuming f() satisfies the right properties and equality means the very same value.) The planner wouldn't need any extra logic to recheck, because the x=a predicate is still there. If there's no index on (x) but there's an index on (f(x)), then we can see if f is a member of a hash opclass, or if it's IMMUTABLE & LEAKPROOF, and I think that's enough. Regards, Jeff Davis
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
shihao zhong <zhong950419@gmail.com>
Дата:
Hi Jeff,
> At this point, the bar is quite high for convincing people to use them.
I agree with that, but I think there are still a decent number of users
who are using hash indexes for different reasons.
I also did some research this afternoon and found that Postgres is the
only mainline DB that still provides an on-disk hash index. So either
we are wrong, or that could be our competitive edge on certain use
cases. I am personally not an expert on hash indexes, so I am not sure
which one I will end up with.
I agree with that, but I think there are still a decent number of users
who are using hash indexes for different reasons.
I also did some research this afternoon and found that Postgres is the
only mainline DB that still provides an on-disk hash index. So either
we are wrong, or that could be our competitive edge on certain use
cases. I am personally not an expert on hash indexes, so I am not sure
which one I will end up with.
Andres said, the long keys problem with btrees is
> incidental, and can be solved other ways.
Looks like this is an interesting problem. I do agree that if there is
any potential optimization for btree, we should take it all. If nobody
volunteers, I can create a different thread and create a POC for it
> incidental, and can be solved other ways.
Looks like this is an interesting problem. I do agree that if there is
any potential optimization for btree, we should take it all. If nobody
volunteers, I can create a different thread and create a POC for it
after 19 GAed.
> If there's no index on (x) but there's an index on (f(x)), then we can
> see if f is a member of a hash opclass, or if it's IMMUTABLE &
> LEAKPROOF, and I think that's enough.
> see if f is a member of a hash opclass, or if it's IMMUTABLE &
> LEAKPROOF, and I think that's enough.
I am not sure. I know some types' = has special logic, where it may not
mean they are the same.
mean they are the same.
For example, 'ABC' = 'abc' is true
with a case-insensitive collation. But md5() gives different results.
with a case-insensitive collation. But md5() gives different results.
Thanks,
Shihao
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
Jeff Davis <pgsql@j-davis.com>
Дата:
On Thu, 2026-10-29 at 22:51 -0400, shihao zhong wrote: > I agree with that, but I think there are still a decent number of > users > who are using hash indexes for different reasons. ... > Looks like this is an interesting problem. I do agree that if there > is > any potential optimization for btree, we should take it all. If > nobody > volunteers, I can create a different thread and create a POC for it > after 19 GAed. Yes, that makes sense to me. If you think there's benefit to be had, please go ahead in a new thread. > > I am not sure. I know some types' = has special logic, where it may > not > mean they are the same. > > For example, 'ABC' = 'abc' is true > with a case-insensitive collation. But md5() gives different results. Right, there are a few details to work out. But I do think there's room to solve this in the optimizer rather than add more special cases to index DDL and the AMs. We could start by saying it only works if f() is part of a hash opclass, or something. Regards, Jeff Davis
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
On Wed, 28 Oct 2026 at 20:24, vignesh C wrote: > > Few comments: > 1. The README, the macro comment, the code comment and the commit > message say such a buffer "never has a full-page image taken". The > code is include_image = needs_backup, so an image is still taken when > needs_backup is true. For example, _hash_freeovflpage() registers the > write buffer with REGBUF_STANDARD | REGBUF_NO_CHANGE, without > REGBUF_NO_IMAGE, when the primary bucket page is the write page and no > tuples are moved onto it. After a checkpoint, that record carries an > ordinary FPI of the page. > + The REGBUF_NO_CHANGE flag indicates that the buffer is registered without > + being modified by this record, and possibly without an exclusive content > + lock (for example, to force a cleanup lock on the block during replay). > + Such a buffer never has a full-page image taken, not even when WAL > + consistency checking is enabled: its contents may change concurrently > > Is this ok, or should we mention like "no consistency-check image" I noticed that the patch has been committed. I thought this comment might have been missed during the discussion, so here is a small follow-up patch to clarify the behavior and avoid confusion: "This does not affect full-page images used for torn-page protection." Regards, Vignesh
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
vignesh C <vignesh21@gmail.com>
Дата:
On Mon, 26 Oct 2026 at 08:48, Michael Paquier wrote: > > Honestly, I am not convinced that it is worth bothering with the > v14~16 branches: REGBUF_NO_CHANGE does not exist there, and we would > need to identify a way to identify pin-only buffers, probably with an > exclusive lock check when a record is assembled, or something like > that. I really cannot get excited by that just for the sake of making > wal_consistency_checking able to work better for hash records there. > So let's leave it at v17~ where the regbuf flag exists. While looking at the back-branch behavior of 27caf4ca5ae, I checked its impact on mixed minor-version replication. Since this changes what the primary writes in back branches (17–19), I wanted to check whether it needs a release note. I tested REL_18 with and without the commit, using both streaming replication and crash recovery. I found one case that fails: a primary with the commit and wal_consistency_checking enabled for hash, streaming to a standby without the commit. The new primary no longer writes a consistency image for the registered NO_CHANGE block. However, the older standby expects an image for every registered block in a flagged record. It stops at the first such record with an assertion failure in an assert build, or a FATAL error otherwise. The standby works normally after it is updated. Without wal_consistency_checking, the WAL remains unchanged. Disabling the setting on the standby does not help because the flag is part of the WAL record. This affects only users who enable wal_consistency_checking in production, but it can cause a standby to stop until it is updated. I was wondering whether we should mention this in the release notes, advising users to update standbys before primaries or disable wal_consistency_checking on the primary until all nodes are updated. Regards, Vignesh
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
On Mon, Nov 02, 2026 at 02:21:58PM +0530, vignesh C wrote: > I was wondering whether we should mention this in the release notes, > advising users to update standbys before primaries or disable > wal_consistency_checking on the primary until all nodes are updated. wal_consistency_checking is a developer option. I doubt that this is worth mentioning in the release notes: nobody should use it in production environments. -- Michael
Re: WAL record CRC calculated incorrectly because of underlying buffer modification
От:
vignesh C <vignesh21@gmail.com>
Дата:
On Mon, 2 Nov 2026 at 16:31, Michael Paquier wrote: > > On Mon, Nov 02, 2026 at 02:21:58PM +0530, vignesh C wrote: > > I was wondering whether we should mention this in the release notes, > > advising users to update standbys before primaries or disable > > wal_consistency_checking on the primary until all nodes are updated. > > wal_consistency_checking is a developer option. I doubt that this is > worth mentioning in the release notes: nobody should use it in > production environments. Thanks, that makes sense. Then nothing else is required for this. Regards, Vignesh