On Thu, Nov 12, 2026 at 2:09 PM Jakub Wartak
<[email protected]> wrote:
>
> On Sun, Nov 8, 2026 at 8:23 AM Andrey Borodin <[email protected]> wrote:
> >
> > Hi Jakub,
>
> Hi Andrey,
>
> > On 5 Oct 2026, Jakub Wartak wrote:
> > > still follows LP_REDIRECT/HOT
> >
> > PFA v7 with your API fixup folded into 0001 and the old 0002/0003 merged.
> [..]
>
> Cool!
>
> I've found two missing things and I'm attaching as one-off patches for
> consideration and some other third small thing:
> 1) pg_amcheck was missing --indexallkeysmatch support
> 2) we could check if btree isn't pointing directly to HOT (just in case)
>
> Also I've been throwing this code under a bus a lot at 100MB and 10GB+ scales
> with over 10k TPS and vacuum hammering it like crazy for dozen of minutes
> (with threshold/scales='1' and with high concurrency pgbench), and I couldn't
> find a single false positives being generated: both on primary and standby
> with parallel pg_amchecks -j X --indexallkeysmatch , on standby of with with
> hot_standby_feedback to avoid rep conflicts).
>
> Also I've made braindump about and come to the conclusion that perhaps the
> below table could be part of docs or just having it in the code would be
> useful, thoughts on this? (perhaps please double check me on this if we
> want to have it in docs)
>
> corruption-kind                                b_i_c()  b_i_parent_c()
> lost heap segment/TID beyond end of heap       yes*   yes*
> index<->heapam key mismatch                    yes    yes
> TID points to LP_UNUSED                        no     yes
> TID offset beyond the page line pointer array  no     yes
> TID points directly at HOT (w/o LP_REDIRECT)   no     yes
>
> * = even without indexallkeysmatch
> b_i_c()  b_i_parent_c() stand for shortcuts of SQL function names.
>
> Anyway, I find the tradeoff betwen lock mode (SL vs ASL) and being able to
> idenitify corrupted things quite good as it is now. Perhaps, we should set
> it as ready for commit now?
>
> Perhaps, qq, should we care if there are other tableAM used with btree
> somehow? (I haven't tried that as I'm struggling to find one that works with
> master/PG20)

This is just to answer myself on the last question (tableAM, got one non-
standard one running on PG20): bt_report_dangling_index_entry() quits if relam
!= HEAP_TABLE_AM_OID, however during the further tests on v7 against
non-heapAM, I've got false errors from bt_check_every_level(). I think we can
assume that TID is a physical location for heapAM, but for other tableAMs this
might be NOT true (they can give TID whatever they like from I can see).

So fix the beyond-EOF check so that it check this only for heapAM. Attached is
set of patches as it was (v7), plus the new one: 0007. @Andrey: if You are happy
with them, they should be just squashed (I didn't want to do it, just to
show the diffs over time). Anyway, the rest of the question about doc probably
and should we switch the CF entry to 'ready for commiter' persists.

-J.
From abebd5dd748b21d554ba970c45531a44845c77ed Mon Sep 17 00:00:00 2001
From: Andrey Borodin <[email protected]>
Date: Sun, 8 Nov 2026 11:17:49 +0500
Subject: [PATCH v16112026 2/7] amcheck: detect dangling B-Tree references to
 heap storage

Check leaf TIDs against heap size regardless of indexallkeysmatch.  Refresh
the size before reporting corruption to allow concurrent extension.  Skip
the check when the main fork is absent, so indexes can still be verified
independently of the missing heap fork.

On a reverse-key lookup that finds no visible tuple, distinguish an unused
or out-of-range heap slot from a dead tuple only with ShareLock.  This
blocks VACUUM from recycling an indexed slot, while allowing opportunistic
pruning of HOT chains.  AccessShareLock cannot make that distinction.

Combine the beyond-EOF checks in one place.  Add tests of dangling slots
and missing segments, including calls with indexallkeysmatch disabled.

Author: Andrey Borodin <[email protected]>
Author: Jakub Wartak <[email protected]>
Reviewed-by: Zsolt Parragi <[email protected]>
Reviewed-by: Wenbo Lin <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 contrib/amcheck/meson.build                   |   2 +
 .../t/008_verify_nbtree_lost_segments.pl      | 121 +++++++++++++
 .../amcheck/t/009_verify_nbtree_dangling.pl   |  82 +++++++++
 contrib/amcheck/verify_nbtree.c               | 166 +++++++++++++++++-
 4 files changed, 369 insertions(+), 2 deletions(-)
 create mode 100644 contrib/amcheck/t/008_verify_nbtree_lost_segments.pl
 create mode 100644 contrib/amcheck/t/009_verify_nbtree_dangling.pl

diff --git a/contrib/amcheck/meson.build b/contrib/amcheck/meson.build
index 220b1ce1d59..68dcbacb226 100644
--- a/contrib/amcheck/meson.build
+++ b/contrib/amcheck/meson.build
@@ -52,6 +52,8 @@ tests += {
       't/005_pitr.pl',
       't/006_verify_gin.pl',
       't/007_verify_nbtree_indexallkeysmatch.pl',
+      't/008_verify_nbtree_lost_segments.pl',
+      't/009_verify_nbtree_dangling.pl',
     ],
   },
 }
diff --git a/contrib/amcheck/t/008_verify_nbtree_lost_segments.pl b/contrib/amcheck/t/008_verify_nbtree_lost_segments.pl
new file mode 100644
index 00000000000..16b44b05041
--- /dev/null
+++ b/contrib/amcheck/t/008_verify_nbtree_lost_segments.pl
@@ -0,0 +1,121 @@
+
+# Copyright (c) 2023-2026, PostgreSQL Global Development Group
+
+# This regression test checks the behavior of the btree validation in the
+# presence of missing relation segments.
+#
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('test');
+$node->init;
+$node->append_conf('postgresql.conf', 'autovacuum = off');
+$node->start;
+
+# Create two tables, one with unique index and another to test
+# posting list (btree duplicates).
+$node->safe_psql(
+	'postgres', q(
+	CREATE EXTENSION amcheck;
+	CREATE TABLE missingsegs_test1 AS
+		SELECT * FROM generate_series(1, 3000) id;
+	CREATE TABLE missingsegs_test2 AS
+		SELECT 10 AS id FROM generate_series(1, 3000);
+	CREATE UNIQUE INDEX bttest_unique_idx1 ON missingsegs_test1 (id);
+	CREATE INDEX bttest_idx2 ON missingsegs_test2 (id);
+));
+
+my ($result, $stdout, $stderr);
+
+# The test tables are small, so a second relation segment only exists when
+# the server was built with a tiny segment size (--with-segsize-blocks).
+# There is no way to simulate a lost segment otherwise; skip in that case.
+my $segpath1 = relation_filepath('missingsegs_test1') . ".1";
+my $segpath2 = relation_filepath('missingsegs_test2') . ".1";
+if (!-e $segpath1 || !-e $segpath2)
+{
+	plan skip_all =>
+	  'test requires small relation segment size (--with-segsize-blocks)';
+}
+
+# We have not yet broken the index, so we should get no corruption
+$result = $node->safe_psql(
+	'postgres', q(
+	SELECT bt_index_check('bttest_unique_idx1', true, true, true);
+));
+is($result, '', 'run amcheck on non-broken bttest_unique_idx1');
+
+$result = $node->safe_psql(
+	'postgres', q(
+	SELECT bt_index_check('bttest_idx2', true, true, true);
+));
+is($result, '', 'run amcheck on non-broken bttest_idx2');
+
+# Break the relations, simulating rogue action or just fsck moving files
+# into the /lost+found.
+my $relpath1 = relation_filepath('missingsegs_test1');
+my $relpath2 = relation_filepath('missingsegs_test2');
+$node->stop;
+corrupt_segment($relpath1 . ".1");
+corrupt_segment($relpath2 . ".1");
+$node->start;
+
+$result = $node->safe_psql(
+	'postgres', q(
+		SET enable_indexscan TO off;
+		SET enable_indexonlyscan TO off;
+		SELECT count(id) FROM missingsegs_test1;
+));
+cmp_ok(3000, '>', $result,
+	"ensure there is missing data on missingsegs_test1");
+
+$result = $node->safe_psql(
+	'postgres', q(
+		SET enable_indexscan TO off;
+		SET enable_indexonlyscan TO off;
+		SELECT count(id) FROM missingsegs_test2;
+));
+cmp_ok(3000, '>', $result,
+	"ensure there is missing data on missingsegs_test2");
+
+# Beyond-EOF checks must not depend on indexallkeysmatch being enabled.
+for my $index ('bttest_unique_idx1', 'bttest_idx2')
+{
+	for my $options ('', ', true, true, true')
+	{
+		($result, $stdout, $stderr) = $node->psql('postgres',
+			qq(SELECT bt_index_check('$index'$options)));
+		is($result, 3, "missing segment rejected by bt_index_check('$index'$options)");
+		like($stderr,
+			qr/index line pointer in index "$index" points to missing page in table/,
+			"missing page identified by bt_index_check('$index'$options)");
+	}
+}
+
+$node->stop;
+done_testing();
+
+# Returns the filesystem path for the named relation.
+sub relation_filepath
+{
+	my ($relname) = @_;
+
+	my $pgdata = $node->data_dir;
+	my $rel = $node->safe_psql('postgres',
+		qq(SELECT pg_relation_filepath('$relname')));
+	die "path not found for relation $relname" unless defined $rel;
+	return "$pgdata/$rel";
+}
+
+# Rename segment so that it is inaccessible.
+sub corrupt_segment
+{
+	my ($relpath) = @_;
+	my $destrelpath = $relpath . ".BAK";
+
+	rename($relpath, $destrelpath)
+	  or BAIL_OUT("rename failed: $!");
+}
diff --git a/contrib/amcheck/t/009_verify_nbtree_dangling.pl b/contrib/amcheck/t/009_verify_nbtree_dangling.pl
new file mode 100644
index 00000000000..a285cab839c
--- /dev/null
+++ b/contrib/amcheck/t/009_verify_nbtree_dangling.pl
@@ -0,0 +1,82 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# An index-referenced heap slot may become LP_DEAD through pruning, but
+# cannot become LP_UNUSED while bt_index_parent_check holds ShareLock.
+# bt_index_check cannot make the same distinction from concurrent VACUUM.
+use strict;
+use warnings FATAL => 'all';
+
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('test');
+$node->init(no_data_checksums => 1);
+$node->append_conf('postgresql.conf', 'autovacuum = off');
+$node->start;
+$node->safe_psql('postgres', q(
+	CREATE EXTENSION amcheck;
+	CREATE EXTENSION pageinspect;
+	CREATE TABLE dangling_unused (id int);
+	INSERT INTO dangling_unused VALUES (1);
+	CREATE INDEX dangling_unused_idx ON dangling_unused (id);
+	CREATE TABLE dangling_offset (id int);
+	INSERT INTO dangling_offset VALUES (1);
+	CREATE INDEX dangling_offset_idx ON dangling_offset (id);
+	CREATE TABLE dangling_dead (id int);
+	INSERT INTO dangling_dead VALUES (1);
+	CREATE INDEX dangling_dead_idx ON dangling_dead (id);
+	DELETE FROM dangling_dead;
+));
+$node->safe_psql('postgres',
+	'VACUUM (INDEX_CLEANUP OFF, TRUNCATE OFF) dangling_dead');
+is($node->safe_psql('postgres', q(
+	SELECT lp_flags FROM heap_page_items(get_raw_page('dangling_dead', 0))
+	WHERE lp = 1;
+)), '3', 'pruning left an LP_DEAD slot awaiting index cleanup');
+is($node->safe_psql('postgres', q(
+	SELECT bt_index_parent_check('dangling_dead_idx', false, false, false, true);
+)), '', 'LP_DEAD is not a dangling index entry');
+
+my %paths;
+for my $table ('dangling_unused', 'dangling_offset')
+{
+	$paths{$table} = $node->data_dir . '/' . $node->safe_psql('postgres',
+		qq(SELECT pg_relation_filepath('$table')));
+}
+$node->stop;
+
+# Zero the first ItemIdData (just after the 24-byte PageHeaderData) to
+# turn the indexed tuple into LP_UNUSED.  Separately, move pd_lower to
+# the end of the page header so that offset 1 is beyond the ItemId array.
+overwrite($paths{dangling_unused}, 24, pack('L', 0));
+overwrite($paths{dangling_offset}, 12, pack('S', 24));
+$node->start;
+
+for my $case (
+	['dangling_unused', qr/points to unused heap slot/],
+	['dangling_offset', qr/with out-of-range offset/])
+{
+	my ($table, $error) = @$case;
+	is($node->safe_psql('postgres',
+		qq(SELECT bt_index_check('${table}_idx', false, false, true))),
+		'', "bt_index_check skips $table without ShareLock");
+	my ($ret, $out, $err) = $node->psql('postgres',
+		qq(SELECT bt_index_parent_check('${table}_idx', false, false, false, true)));
+	is($ret, 3, "bt_index_parent_check rejects $table");
+	like($err, $error, "bt_index_parent_check identifies $table");
+}
+
+$node->stop;
+done_testing();
+
+sub overwrite
+{
+	my ($path, $offset, $bytes) = @_;
+	open(my $fh, '+<', $path) or BAIL_OUT("open failed: $!");
+	binmode $fh;
+	defined(sysseek($fh, $offset, 0)) or BAIL_OUT("sysseek failed: $!");
+	syswrite($fh, $bytes) == length($bytes)
+	  or BAIL_OUT("syswrite failed: $!");
+	close($fh) or BAIL_OUT("close failed: $!");
+}
diff --git a/contrib/amcheck/verify_nbtree.c b/contrib/amcheck/verify_nbtree.c
index 94e43a23e52..59516bde6e6 100644
--- a/contrib/amcheck/verify_nbtree.c
+++ b/contrib/amcheck/verify_nbtree.c
@@ -151,6 +151,8 @@ typedef struct BtreeCheckState
 	/* Reusable slot and executor state for FormIndexDatum() */
 	TupleTableSlot *iakm_slot;
 	EState	   *iakm_estate;
+	/* Cached heap size for unconditional beyond-EOF verification */
+	BlockNumber heapnblocks;
 } BtreeCheckState;
 
 /*
@@ -239,6 +241,10 @@ static void bt_verify_index_tuple_points_to_heap(BtreeCheckState *state,
 												 IndexTuple itup,
 												 BlockNumber targetblock,
 												 OffsetNumber offset);
+static void bt_report_dangling_index_entry(BtreeCheckState *state,
+										   ItemPointer tid,
+										   BlockNumber targetblock,
+										   OffsetNumber offset);
 static IndexTuple bt_normalize_tuple(BtreeCheckState *state,
 									 IndexTuple itup);
 static inline IndexTuple bt_posting_plain_tuple(IndexTuple itup, int n);
@@ -432,6 +438,18 @@ bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace,
 	state->heaprel = heaprel;
 	state->heapkeyspace = heapkeyspace;
 	state->readonly = readonly;
+
+	/*
+	 * Remember the current size of the heap for beyond-EOF TID checks.  When
+	 * the main fork is missing entirely, skip those checks (by making any
+	 * comparison against heapnblocks false): the user may have deliberately
+	 * excluded the corrupt table from table-level verification, which is what
+	 * reports a missing main fork.
+	 */
+	if (smgrexists(RelationGetSmgr(state->heaprel), MAIN_FORKNUM))
+		state->heapnblocks = RelationGetNumberOfBlocks(state->heaprel);
+	else
+		state->heapnblocks = InvalidBlockNumber;
 	state->heapallindexed = heapallindexed;
 	state->indexallkeysmatch = indexallkeysmatch;
 	state->rootdescend = rootdescend;
@@ -1614,6 +1632,63 @@ bt_target_page_check(BtreeCheckState *state)
 			}
 		}
 
+		/* Check that leaf page tuples do not point beyond the end of heap */
+		if (P_ISLEAF(topaque) && !ItemIdIsDead(itemid))
+		{
+			int			nposting = 1;
+			int			i;
+
+			if (BTreeTupleIsPosting(itup))
+				nposting = BTreeTupleGetNPosting(itup);
+
+			for (i = 0; i < nposting; i++)
+			{
+				ItemPointer htid;
+				BlockNumber heapblk;
+				OffsetNumber heapoff;
+
+				if (nposting > 1)
+					htid = BTreeTupleGetPostingN(itup, i);
+				else
+					htid = BTreeTupleGetPointsToTID(itup);
+
+				heapblk = ItemPointerGetBlockNumber(htid);
+				heapoff = ItemPointerGetOffsetNumber(htid);
+
+				/*
+				 * Does heapblk go beyond RelationGetNumberOfBlocks(),
+				 * potentially indicating a missing relation segment?
+				 */
+				if (state->heapnblocks != InvalidBlockNumber &&
+					heapblk >= state->heapnblocks)
+				{
+					/*
+					 * The relation may have been extended concurrently;
+					 * refresh the cached value before reporting corruption.
+					 */
+					state->heapnblocks = RelationGetNumberOfBlocks(state->heaprel);
+					if (heapblk >= state->heapnblocks)
+					{
+						char	   *postingoff = "";
+
+						if (nposting > 1)
+							postingoff = psprintf(" posting list offset=%d", i);
+
+						ereport(ERROR,
+								(errcode(ERRCODE_INDEX_CORRUPTED),
+								 errmsg("index line pointer in index \"%s\" points to missing page in table \"%s\"",
+										RelationGetRelationName(state->rel),
+										RelationGetRelationName(state->heaprel)),
+								 errdetail_internal("Index tid=(%u,%u)%s points to heap tid=(%u,%u) but heap has only %u blocks.",
+													state->targetblock, offset, postingoff,
+													heapblk, heapoff,
+													state->heapnblocks),
+								 errhint("This can be caused by a lost relation segment (missing or removed file).")));
+					}
+				}
+			}
+		}
+
 		/* Verify each index tuple points to heap tuple with same key */
 		if (state->indexallkeysmatch && P_ISLEAF(topaque) && !ItemIdIsDead(itemid))
 		{
@@ -2972,8 +3047,10 @@ bt_heap_fingerprint_callback(Relation index, ItemPointer tid, Datum *values,
  * chains, resolving the TID of the visible tuple version, which we then
  * load into a slot with table_tuple_fetch_row_version().  A "not found"
  * result means the tuple is dead or was concurrently pruned; we skip it
- * exactly as an index scan would.  Here we verify that the visible
- * heap tuple matches the index key.
+ * exactly as an index scan would.  Detecting index entries that point to
+ * nonexistent heap slots is a separate class of corruption, handled
+ * elsewhere; what we verify here is that the visible heap tuple matches the
+ * index key.
  */
 static void
 bt_verify_index_tuple_points_to_heap(BtreeCheckState *state, IndexTuple itup,
@@ -3022,7 +3099,18 @@ bt_verify_index_tuple_points_to_heap(BtreeCheckState *state, IndexTuple itup,
 		 */
 		visibletid = *tid;
 		if (!table_fetch_tid(state->heaprel, &visibletid, state->snapshot, NULL))
+		{
+			/*
+			 * No visible tuple at this TID.  Normally that just means the
+			 * index entry is for a dead (or concurrently pruned) heap tuple
+			 * and there is nothing to compare, but it can also mean the index
+			 * entry is dangling: pointing to a heap slot that holds no tuple
+			 * at all.  Try to tell these cases apart when it is safe to do
+			 * so.
+			 */
+			bt_report_dangling_index_entry(state, tid, targetblock, offset);
 			return;
+		}
 
 		if (!table_tuple_fetch_row_version(state->heaprel, &visibletid,
 										   state->snapshot, slot))
@@ -3061,6 +3149,80 @@ bt_verify_index_tuple_points_to_heap(BtreeCheckState *state, IndexTuple itup,
 	}
 }
 
+/*
+ * Try to detect a dangling index entry: an index tuple whose TID points to
+ * a heap slot that holds no tuple at all (as opposed to a dead one awaiting
+ * VACUUM).  Called when an MVCC fetch of the TID found no visible tuple.
+ *
+ * References beyond the end of the heap have already been checked in
+ * bt_target_page_check(), independently of indexallkeysmatch.
+ *
+ * Distinguishing other dangling cases (out-of-range offset, LP_UNUSED slot)
+ * from a concurrently pruned tuple requires that the heap slot cannot
+ * change under us.  Under ShareLock (bt_index_parent_check) concurrent
+ * VACUUM is blocked, so an index-referenced slot cannot become LP_UNUSED
+ * and the line pointer array cannot be truncated: opportunistic pruning may
+ * mark slots LP_DEAD or redirect them, but it only marks HOT-chain member
+ * slots LP_UNUSED, and those are never referenced from indexes.  Under
+ * AccessShareLock (bt_index_check) concurrent VACUUM may reclaim the slot
+ * between our Bloom filter probe and the fetch, so we must not report
+ * anything.
+ *
+ * Direct line pointer inspection requires heap page layout, so it is
+ * skipped for non-heap table AMs.
+ */
+static void
+bt_report_dangling_index_entry(BtreeCheckState *state, ItemPointer tid,
+							   BlockNumber targetblock, OffsetNumber offset)
+{
+	BlockNumber blkno = ItemPointerGetBlockNumber(tid);
+	OffsetNumber offnum = ItemPointerGetOffsetNumber(tid);
+	Buffer		buffer;
+	Page		page;
+	ItemId		lp;
+
+	/*
+	 * Without ShareLock a missing slot is indistinguishable from a
+	 * concurrently pruned tuple; report nothing.
+	 */
+	if (!state->readonly)
+		return;
+
+	/* Line pointer inspection below assumes heap page layout */
+	if (state->heaprel->rd_rel->relam != HEAP_TABLE_AM_OID)
+		return;
+
+	buffer = ReadBufferExtended(state->heaprel, MAIN_FORKNUM, blkno,
+								RBM_NORMAL, state->checkstrategy);
+	LockBuffer(buffer, BUFFER_LOCK_SHARE);
+	page = BufferGetPage(buffer);
+
+	if (offnum > PageGetMaxOffsetNumber(page))
+		ereport(ERROR,
+				(errcode(ERRCODE_INDEX_CORRUPTED),
+				 errmsg("index tuple in index \"%s\" points to heap tuple in table \"%s\" with out-of-range offset",
+						RelationGetRelationName(state->rel),
+						RelationGetRelationName(state->heaprel)),
+				 errdetail_internal("Index tid=(%u,%u) points to heap tid=(%u,%u), but page has only %u line pointers.",
+									targetblock, offset,
+									blkno, offnum,
+									(unsigned) PageGetMaxOffsetNumber(page))));
+
+	lp = PageGetItemId(page, offnum);
+	if (!ItemIdIsUsed(lp))
+		ereport(ERROR,
+				(errcode(ERRCODE_INDEX_CORRUPTED),
+				 errmsg("index tuple in index \"%s\" points to unused heap slot in table \"%s\"",
+						RelationGetRelationName(state->rel),
+						RelationGetRelationName(state->heaprel)),
+				 errdetail_internal("Index tid=(%u,%u) points to heap tid=(%u,%u) marked LP_UNUSED.",
+									targetblock, offset,
+									blkno, offnum)));
+
+	/* LP_DEAD, LP_REDIRECT or a dead LP_NORMAL tuple: not corruption */
+	UnlockReleaseBuffer(buffer);
+}
+
 /*
  * Normalize an index tuple for fingerprinting.
  *
-- 
2.43.0

From e60c6bc91e9ddba9fb95deda6b873b4994446db9 Mon Sep 17 00:00:00 2001
From: Andrey Borodin <[email protected]>
Date: Sun, 8 Nov 2026 11:18:25 +0500
Subject: [PATCH v16112026 3/7] doc: describe indexallkeysmatch verification

Document the additional dedicated full heap scan, Bloom-filter memory and
false-positive limits, and the lock-dependent treatment of unused heap
slots.  Describe the unconditional beyond-EOF check separately from the
optional reverse-key verification.

Author: Andrey Borodin <[email protected]>
Author: Jakub Wartak <[email protected]>
Reviewed-by: Zsolt Parragi <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 doc/src/sgml/amcheck.sgml | 81 ++++++++++++++++++++++++++++++++++++---
 1 file changed, 75 insertions(+), 6 deletions(-)

diff --git a/doc/src/sgml/amcheck.sgml b/doc/src/sgml/amcheck.sgml
index 13a6bb18897..e465ce06efc 100644
--- a/doc/src/sgml/amcheck.sgml
+++ b/doc/src/sgml/amcheck.sgml
@@ -61,7 +61,7 @@
   <variablelist>
    <varlistentry>
     <term>
-     <function>bt_index_check(index regclass, heapallindexed boolean, checkunique boolean) returns void</function>
+     <function>bt_index_check(index regclass, heapallindexed boolean, checkunique boolean, indexallkeysmatch boolean) returns void</function>
      <indexterm>
       <primary>bt_index_check</primary>
      </indexterm>
@@ -118,7 +118,10 @@ ORDER BY c.relpages DESC LIMIT 10;
       that span child/parent relationships, but will verify the
       presence of all heap tuples as index tuples within the index
       when <parameter>heapallindexed</parameter> is
-      <literal>true</literal>.  When <parameter>checkunique</parameter>
+      <literal>true</literal>.  When <parameter>indexallkeysmatch</parameter>
+      is <literal>true</literal>, it verifies that each index tuple
+      points to a heap tuple with the same key (the reverse of
+      <parameter>heapallindexed</parameter>).  When <parameter>checkunique</parameter>
       is <literal>true</literal> <function>bt_index_check</function> will
       check that no more than one among duplicate entries in unique
       index is visible.  When a routine, lightweight test for
@@ -127,12 +130,20 @@ ORDER BY c.relpages DESC LIMIT 10;
       trade-off between thoroughness of verification and limiting the
       impact on application performance and availability.
      </para>
+     <para>
+      Both B-Tree checking functions report index tuples that point to heap
+      blocks beyond the end of the table, even when
+      <parameter>indexallkeysmatch</parameter> is <literal>false</literal>.
+      This can detect a lost relation segment.  The check is skipped if the
+      table's main relation fork is absent, allowing indexes to be checked
+      independently of heap verification.
+     </para>
     </listitem>
    </varlistentry>
 
    <varlistentry>
     <term>
-     <function>bt_index_parent_check(index regclass, heapallindexed boolean, rootdescend boolean, checkunique boolean) returns void</function>
+     <function>bt_index_parent_check(index regclass, heapallindexed boolean, rootdescend boolean, checkunique boolean, indexallkeysmatch boolean) returns void</function>
      <indexterm>
       <primary>bt_index_parent_check</primary>
      </indexterm>
@@ -145,7 +156,9 @@ ORDER BY c.relpages DESC LIMIT 10;
       Optionally, when the <parameter>heapallindexed</parameter>
       argument is <literal>true</literal>, the function verifies the
       presence of all heap tuples that should be found within the
-      index.  When <parameter>checkunique</parameter>
+      index.  When <parameter>indexallkeysmatch</parameter> is
+      <literal>true</literal>, it verifies that each index tuple
+      points to a heap tuple with the same key.  When <parameter>checkunique</parameter>
       is <literal>true</literal> <function>bt_index_parent_check</function> will
       check that no more than one among duplicate entries in unique
       index is visible.  When the optional <parameter>rootdescend</parameter>
@@ -413,6 +426,59 @@ SET client_min_messages = DEBUG1;
   single absent or malformed tuple has a new opportunity to be
   detected with each new verification attempt.
  </para>
+ <para>
+  When both <parameter>heapallindexed</parameter> and
+  <parameter>indexallkeysmatch</parameter> are enabled, two Bloom
+  filters are allocated, each up to <varname>maintenance_work_mem</varname>.
+ </para>
+
+ </sect2>
+
+ <sect2 id="amcheck-optional-indexallkeysmatch-verification">
+  <title>Optional <parameter>indexallkeysmatch</parameter> Verification</title>
+ <para>
+  When the <parameter>indexallkeysmatch</parameter> argument to B-Tree
+  verification functions is <literal>true</literal>, an additional
+  phase verifies that each index tuple points to a heap tuple with the
+  same key.  This is the reverse of <parameter>heapallindexed</parameter>:
+  <parameter>heapallindexed</parameter> checks that every heap tuple is
+  in the index, while <parameter>indexallkeysmatch</parameter> checks
+  that every index tuple points to a matching heap tuple.
+ </para>
+ <para>
+  The implementation uses a Bloom filter to amortize random heap
+  lookups.  An additional dedicated full sequential heap scan first
+  fingerprints all visible (key, tid) pairs.  This scan is required even
+  when <parameter>heapallindexed</parameter> is also enabled, and can be
+  expensive for large tables.  During the index scan, each leaf tuple is probed
+  against this filter.  Only when the filter says &quot;not present&quot; does
+  an actual heap fetch and key comparison occur.  Corruption is
+  reported when the heap tuple's key (as computed by
+  <function>FormIndexDatum</function>) differs from the index tuple's
+  key.
+  Additionally, <function>bt_index_parent_check</function>
+  reports index tuples pointing to unused heap slots; under the weaker
+  lock taken by <function>bt_index_check</function> such slots cannot
+  be reliably distinguished from tuples concurrently removed by
+  <command>VACUUM</command>, so they are skipped.
+ </para>
+ <para>
+  Like <parameter>heapallindexed</parameter>, this check requires an
+  MVCC snapshot to obtain a consistent view of the heap and index.
+  The heap lookup follows <acronym>HOT</acronym> chains the same way a
+  regular index scan does.  Heap tuple versions not visible to the
+  snapshot are not compared.
+ </para>
+ <para>
+  The summarizing structure is bound in size by
+  <varname>maintenance_work_mem</varname>, using the same sizing
+  approach as <parameter>heapallindexed</parameter>.  In order to ensure
+  that there is no more than a 2% probability of failure to detect an
+  inconsistency for each index tuple that should match a heap tuple,
+  approximately 2 bytes of memory are needed per tuple.  As less memory
+  is made available per tuple, the probability of missing an
+  inconsistency slowly increases.
+ </para>
 
  </sect2>
 
@@ -457,12 +523,15 @@ SET client_min_messages = DEBUG1;
    <listitem>
     <para>
      Structural inconsistencies between indexes and the heap relations
-     that are indexed (when <parameter>heapallindexed</parameter>
-     verification is performed).
+     that are indexed (when <parameter>heapallindexed</parameter> or
+     <parameter>indexallkeysmatch</parameter> verification is performed).
     </para>
     <para>
      There is no cross-checking of indexes against their heap relation
      during normal operation.  Symptoms of heap corruption can be subtle.
+     <parameter>indexallkeysmatch</parameter> detects cases where an index
+     tuple stores a different key than the heap tuple it points to, or
+     points to a non-existent heap slot.
     </para>
    </listitem>
    <listitem>
-- 
2.43.0

From e977e472e6c11f6f72d800925a25e0bb708c0b7c Mon Sep 17 00:00:00 2001
From: Andrey Borodin <[email protected]>
Date: Sun, 8 Nov 2026 11:17:10 +0500
Subject: [PATCH v16112026 1/7] amcheck: add indexallkeysmatch verification for
 B-Tree indexes

Add an optional reverse check that index tuples agree with visible heap
tuples.  Fingerprint heap (key, TID) pairs in a Bloom filter before scanning
the index, and fetch tuples on Bloom misses to verify their keys.  Reuse a
slot and executor state for these lookups and normalize both representations
with the existing heapallindexed machinery.

Use table_fetch_tid() to resolve HOT chains and LP_REDIRECT before fetching
the visible row version.  Retain the original indexed TID for comparison.
Cover both HOT states with forced key mismatches, and exercise the existing
varlena normalization cases with the new option enabled.

Author: Andrey Borodin <[email protected]>
Author: Jakub Wartak <[email protected]>
Reviewed-by: Zsolt Parragi <[email protected]>
Reviewed-by: Wenbo Lin <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 contrib/amcheck/Makefile                      |   4 +-
 contrib/amcheck/amcheck--1.5--1.6.sql         |  21 ++
 contrib/amcheck/amcheck.control               |   2 +-
 contrib/amcheck/expected/check_btree.out      |  26 +-
 contrib/amcheck/meson.build                   |   2 +
 contrib/amcheck/sql/check_btree.sql           |  13 +-
 .../t/007_verify_nbtree_indexallkeysmatch.pl  | 178 ++++++++++
 contrib/amcheck/verify_nbtree.c               | 332 ++++++++++++++++--
 8 files changed, 533 insertions(+), 45 deletions(-)
 create mode 100644 contrib/amcheck/amcheck--1.5--1.6.sql
 create mode 100644 contrib/amcheck/t/007_verify_nbtree_indexallkeysmatch.pl

diff --git a/contrib/amcheck/Makefile b/contrib/amcheck/Makefile
index 1b7a63cbaa4..fdf5970de25 100644
--- a/contrib/amcheck/Makefile
+++ b/contrib/amcheck/Makefile
@@ -10,12 +10,12 @@ OBJS = \
 
 EXTENSION = amcheck
 DATA = amcheck--1.2--1.3.sql amcheck--1.1--1.2.sql amcheck--1.0--1.1.sql amcheck--1.0.sql \
-		amcheck--1.3--1.4.sql amcheck--1.4--1.5.sql
+		amcheck--1.3--1.4.sql amcheck--1.4--1.5.sql amcheck--1.5--1.6.sql
 PGFILEDESC = "amcheck - function for verifying relation integrity"
 
 REGRESS = check check_btree check_gin check_heap
 
-EXTRA_INSTALL = contrib/pg_walinspect
+EXTRA_INSTALL = contrib/pg_walinspect contrib/pageinspect
 TAP_TESTS = 1
 
 ifdef USE_PGXS
diff --git a/contrib/amcheck/amcheck--1.5--1.6.sql b/contrib/amcheck/amcheck--1.5--1.6.sql
new file mode 100644
index 00000000000..ac01f429d7d
--- /dev/null
+++ b/contrib/amcheck/amcheck--1.5--1.6.sql
@@ -0,0 +1,21 @@
+/* contrib/amcheck/amcheck--1.5--1.6.sql */
+
+-- complain if script is sourced in psql, rather than via CREATE EXTENSION
+\echo Use "ALTER EXTENSION amcheck UPDATE TO '1.6'" to load this file. \quit
+
+-- Add indexallkeysmatch parameter to bt_index_check and bt_index_parent_check
+CREATE FUNCTION bt_index_check(index regclass,
+    heapallindexed boolean, checkunique boolean, indexallkeysmatch boolean)
+RETURNS VOID
+AS 'MODULE_PATHNAME', 'bt_index_check'
+LANGUAGE C STRICT PARALLEL RESTRICTED;
+
+CREATE FUNCTION bt_index_parent_check(index regclass,
+    heapallindexed boolean, rootdescend boolean, checkunique boolean,
+    indexallkeysmatch boolean)
+RETURNS VOID
+AS 'MODULE_PATHNAME', 'bt_index_parent_check'
+LANGUAGE C STRICT PARALLEL RESTRICTED;
+
+REVOKE ALL ON FUNCTION bt_index_check(regclass, boolean, boolean, boolean) FROM PUBLIC;
+REVOKE ALL ON FUNCTION bt_index_parent_check(regclass, boolean, boolean, boolean, boolean) FROM PUBLIC;
diff --git a/contrib/amcheck/amcheck.control b/contrib/amcheck/amcheck.control
index c8ba6d7c9bc..2f329ef2cf4 100644
--- a/contrib/amcheck/amcheck.control
+++ b/contrib/amcheck/amcheck.control
@@ -1,5 +1,5 @@
 # amcheck extension
 comment = 'functions for verifying relation integrity'
-default_version = '1.5'
+default_version = '1.6'
 module_pathname = '$libdir/amcheck'
 relocatable = true
diff --git a/contrib/amcheck/expected/check_btree.out b/contrib/amcheck/expected/check_btree.out
index 4fcee5da463..9b7f2ddb9aa 100644
--- a/contrib/amcheck/expected/check_btree.out
+++ b/contrib/amcheck/expected/check_btree.out
@@ -179,7 +179,7 @@ WHERE attrelid = 'toast_bug'::regclass AND attname = 'buggy';
 -- Insert compressible heap tuple (comfortably exceeds TOAST_TUPLE_THRESHOLD):
 INSERT INTO toast_bug SELECT repeat('a', 2200);
 -- Should not get false positive report of corruption:
-SELECT bt_index_check('toasty', true);
+SELECT bt_index_check('toasty', true, false, true);
  bt_index_check 
 ----------------
  
@@ -245,6 +245,26 @@ SELECT bt_index_parent_check('bttest_b_idx', heapallindexed => true, rootdescend
  
 (1 row)
 
+-- indexallkeysmatch: verify each index tuple points to heap tuple with same key
+SELECT bt_index_check('bttest_a_idx', heapallindexed => false, checkunique => false, indexallkeysmatch => true);
+ bt_index_check 
+----------------
+ 
+(1 row)
+
+SELECT bt_index_parent_check('bttest_a_idx', heapallindexed => false, rootdescend => false, checkunique => false, indexallkeysmatch => true);
+ bt_index_parent_check 
+-----------------------
+ 
+(1 row)
+
+-- indexallkeysmatch on expression index (exercises FormIndexDatum/ii_ExpressionsState path)
+SELECT bt_index_check('bttest_a_expr_idx', heapallindexed => false, checkunique => false, indexallkeysmatch => true);
+ bt_index_check 
+----------------
+ 
+(1 row)
+
 -- Check that null values in an unique index are not treated as equal
 CREATE TABLE bttest_unique_nulls (a serial, b int, c int UNIQUE);
 INSERT INTO bttest_unique_nulls VALUES (generate_series(1, 10000), 2, default);
@@ -267,7 +287,7 @@ ALTER TABLE varlena_bug ALTER column v SET storage plain;
 INSERT INTO varlena_bug VALUES ('x');
 COPY varlena_bug from stdin;
 CREATE INDEX varlena_bug_idx on varlena_bug(v);
-SELECT bt_index_check('varlena_bug_idx', true);
+SELECT bt_index_check('varlena_bug_idx', true, false, true);
  bt_index_check 
 ----------------
  
@@ -277,7 +297,7 @@ SELECT bt_index_check('varlena_bug_idx', true);
 -- uncompressed in index.
 INSERT INTO varlena_bug VALUES (repeat('Test', 250));
 ALTER TABLE varlena_bug ALTER COLUMN v SET STORAGE extended;
-SELECT bt_index_check('varlena_bug_idx', true);
+SELECT bt_index_check('varlena_bug_idx', true, false, true);
  bt_index_check 
 ----------------
  
diff --git a/contrib/amcheck/meson.build b/contrib/amcheck/meson.build
index d5137ef691d..220b1ce1d59 100644
--- a/contrib/amcheck/meson.build
+++ b/contrib/amcheck/meson.build
@@ -27,6 +27,7 @@ install_data(
   'amcheck--1.2--1.3.sql',
   'amcheck--1.3--1.4.sql',
   'amcheck--1.4--1.5.sql',
+  'amcheck--1.5--1.6.sql',
   kwargs: contrib_data_args,
 )
 
@@ -50,6 +51,7 @@ tests += {
       't/004_verify_nbtree_unique.pl',
       't/005_pitr.pl',
       't/006_verify_gin.pl',
+      't/007_verify_nbtree_indexallkeysmatch.pl',
     ],
   },
 }
diff --git a/contrib/amcheck/sql/check_btree.sql b/contrib/amcheck/sql/check_btree.sql
index a5585085fad..91468b973d6 100644
--- a/contrib/amcheck/sql/check_btree.sql
+++ b/contrib/amcheck/sql/check_btree.sql
@@ -120,7 +120,7 @@ WHERE attrelid = 'toast_bug'::regclass AND attname = 'buggy';
 -- Insert compressible heap tuple (comfortably exceeds TOAST_TUPLE_THRESHOLD):
 INSERT INTO toast_bug SELECT repeat('a', 2200);
 -- Should not get false positive report of corruption:
-SELECT bt_index_check('toasty', true);
+SELECT bt_index_check('toasty', true, false, true);
 
 --
 -- Check that index expressions and predicates are run as the table's owner,
@@ -160,6 +160,13 @@ SELECT bt_index_check('bttest_b_idx', heapallindexed => false, checkunique => tr
 SELECT bt_index_parent_check('bttest_a_idx', heapallindexed => true, rootdescend => true, checkunique => true);
 SELECT bt_index_parent_check('bttest_b_idx', heapallindexed => true, rootdescend => false, checkunique => true);
 
+-- indexallkeysmatch: verify each index tuple points to heap tuple with same key
+SELECT bt_index_check('bttest_a_idx', heapallindexed => false, checkunique => false, indexallkeysmatch => true);
+SELECT bt_index_parent_check('bttest_a_idx', heapallindexed => false, rootdescend => false, checkunique => false, indexallkeysmatch => true);
+
+-- indexallkeysmatch on expression index (exercises FormIndexDatum/ii_ExpressionsState path)
+SELECT bt_index_check('bttest_a_expr_idx', heapallindexed => false, checkunique => false, indexallkeysmatch => true);
+
 -- Check that null values in an unique index are not treated as equal
 CREATE TABLE bttest_unique_nulls (a serial, b int, c int UNIQUE);
 INSERT INTO bttest_unique_nulls VALUES (generate_series(1, 10000), 2, default);
@@ -175,13 +182,13 @@ COPY varlena_bug from stdin;
 x
 \.
 CREATE INDEX varlena_bug_idx on varlena_bug(v);
-SELECT bt_index_check('varlena_bug_idx', true);
+SELECT bt_index_check('varlena_bug_idx', true, false, true);
 
 -- Also check that we compress varlena values, which were previously stored
 -- uncompressed in index.
 INSERT INTO varlena_bug VALUES (repeat('Test', 250));
 ALTER TABLE varlena_bug ALTER COLUMN v SET STORAGE extended;
-SELECT bt_index_check('varlena_bug_idx', true);
+SELECT bt_index_check('varlena_bug_idx', true, false, true);
 
 -- cleanup
 DROP TABLE bttest_a;
diff --git a/contrib/amcheck/t/007_verify_nbtree_indexallkeysmatch.pl b/contrib/amcheck/t/007_verify_nbtree_indexallkeysmatch.pl
new file mode 100644
index 00000000000..349a85befec
--- /dev/null
+++ b/contrib/amcheck/t/007_verify_nbtree_indexallkeysmatch.pl
@@ -0,0 +1,178 @@
+
+# Copyright (c) 2026, PostgreSQL Global Development Group
+#
+# Test indexallkeysmatch verification: each index tuple must point to a heap
+# tuple with the same key.
+
+use strict;
+use warnings FATAL => 'all';
+
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node = PostgreSQL::Test::Cluster->new('test');
+$node->init;
+$node->append_conf('postgresql.conf', 'autovacuum=off');
+$node->start;
+
+$node->safe_psql('postgres', q(
+	CREATE EXTENSION amcheck;
+	CREATE EXTENSION pageinspect;
+));
+
+#
+# Test 1: indexallkeysmatch on uncorrupted table (plain column)
+#
+$node->safe_psql('postgres', q(
+	CREATE TABLE idxall_plain (id int);
+	INSERT INTO idxall_plain SELECT generate_series(1, 1000);
+	CREATE INDEX idxall_plain_idx ON idxall_plain (id);
+));
+
+my $result = $node->safe_psql('postgres',
+	q(SELECT bt_index_check('idxall_plain_idx', false, false, true)));
+is($result, '', 'indexallkeysmatch passes on uncorrupted plain table');
+
+#
+# Test 2: indexallkeysmatch on uncorrupted table with deduplication
+#
+$node->safe_psql('postgres', q(
+	CREATE TABLE idxall_dedup (id int);
+	INSERT INTO idxall_dedup SELECT i % 10 FROM generate_series(1, 1000) i;
+	CREATE INDEX idxall_dedup_idx ON idxall_dedup (id)
+		WITH (deduplicate_items = on);
+));
+
+$result = $node->safe_psql('postgres',
+	q(SELECT bt_index_check('idxall_dedup_idx', false, false, true)));
+is($result, '', 'indexallkeysmatch passes on uncorrupted table with deduplication');
+
+#
+# Test 3: indexallkeysmatch on uncorrupted expression index
+#
+$node->safe_psql('postgres', q(
+	CREATE FUNCTION idxall_func(int) RETURNS int LANGUAGE sql IMMUTABLE AS
+	$$ SELECT $1; $$;
+
+	CREATE TABLE idxall_expr (id int);
+	INSERT INTO idxall_expr SELECT generate_series(1, 500);
+	CREATE INDEX idxall_expr_idx ON idxall_expr (idxall_func(id));
+));
+
+$result = $node->safe_psql('postgres',
+	q(SELECT bt_index_check('idxall_expr_idx', false, false, true)));
+is($result, '', 'indexallkeysmatch passes on uncorrupted expression index');
+
+#
+# Test 4: Detect corruption -- swap expression function so heap re-evaluation
+# produces different keys than what the index stores.
+#
+# The index was built with idxall_func(x) = x.  Now change it to return x+1.
+# This simulates the corruption scenario: index says key=42 for a TID, but
+# re-reading the heap and re-evaluating gives key=43.
+#
+$node->safe_psql('postgres', q(
+	CREATE OR REPLACE FUNCTION idxall_func(int) RETURNS int LANGUAGE sql IMMUTABLE AS
+	$$ SELECT $1 + 1; $$;
+));
+
+my ($stdout, $stderr);
+($result, $stdout, $stderr) = $node->psql('postgres',
+	q(SELECT bt_index_check('idxall_expr_idx', false, false, true)));
+like($stderr,
+	qr/index tuple in index "idxall_expr_idx" does not match heap tuple/,
+	'detected index-heap key mismatch via expression function swap');
+
+#
+# Test 5: Restore function and verify no corruption reported
+#
+$node->safe_psql('postgres', q(
+	CREATE OR REPLACE FUNCTION idxall_func(int) RETURNS int LANGUAGE sql IMMUTABLE AS
+	$$ SELECT $1; $$;
+));
+
+$result = $node->safe_psql('postgres',
+	q(SELECT bt_index_check('idxall_expr_idx', false, false, true)));
+is($result, '', 'indexallkeysmatch passes after restoring correct function');
+
+#
+# Test 6: indexallkeysmatch with bt_index_parent_check
+#
+$node->safe_psql('postgres', q(
+	CREATE OR REPLACE FUNCTION idxall_func(int) RETURNS int LANGUAGE sql IMMUTABLE AS
+	$$ SELECT $1 + 1; $$;
+));
+
+($result, $stdout, $stderr) = $node->psql('postgres',
+	q(SELECT bt_index_parent_check('idxall_expr_idx', false, false, false, true)));
+like($stderr,
+	qr/index tuple in index "idxall_expr_idx" does not match heap tuple/,
+	'bt_index_parent_check also detects index-heap key mismatch');
+
+# A HOT update leaves the index pointing to the root, not the visible tuple.
+# Hold an old snapshot to prevent pruning, then release it and VACUUM to
+# exercise LP_REDIRECT as well.  Changing the expression forces Bloom misses:
+# a successful check of an uncorrupted index alone need not fetch any tuples.
+$node->safe_psql('postgres', q(
+	CREATE FUNCTION idxall_hot_func(int) RETURNS int LANGUAGE sql IMMUTABLE AS
+	$$ SELECT $1; $$;
+	CREATE TABLE idxall_hot (id int, payload int) WITH (fillfactor = 10);
+	INSERT INTO idxall_hot SELECT i, 0 FROM generate_series(1, 10) i;
+	CREATE INDEX idxall_hot_idx ON idxall_hot (idxall_hot_func(id));
+));
+my $holder = $node->background_psql('postgres');
+$holder->query_safe(q(
+	BEGIN ISOLATION LEVEL REPEATABLE READ;
+	SELECT count(*) FROM idxall_hot;
+));
+$node->safe_psql('postgres', 'UPDATE idxall_hot SET payload = 1');
+is($node->safe_psql('postgres', q(
+	SELECT count(*) FROM heap_page_items(get_raw_page('idxall_hot', 0))
+	WHERE lp_flags = 1 AND (t_infomask2 & 16384) <> 0;
+)), '10', 'HOT roots remain normal line pointers before pruning');
+check_hot_chain('unpruned HOT chain');
+
+$holder->query_safe('COMMIT');
+$holder->quit;
+$node->safe_psql('postgres', 'VACUUM idxall_hot');
+is($node->safe_psql('postgres', q(
+	SELECT count(*) FROM heap_page_items(get_raw_page('idxall_hot', 0))
+	WHERE lp_flags = 2;
+)), '10', 'VACUUM converted HOT roots to LP_REDIRECT');
+check_hot_chain('LP_REDIRECT');
+
+$node->stop;
+done_testing();
+
+sub check_hot_chain
+{
+	my ($description) = @_;
+
+	for my $function ('bt_index_check', 'bt_index_parent_check')
+	{
+		my $extra = $function eq 'bt_index_check' ? 'false' : 'false, false';
+		is($node->safe_psql('postgres',
+			qq(SELECT $function('idxall_hot_idx', true, $extra, true))),
+			'', "$function accepts $description");
+	}
+
+	$node->safe_psql('postgres', q(
+		CREATE OR REPLACE FUNCTION idxall_hot_func(int) RETURNS int
+		LANGUAGE sql IMMUTABLE AS $$ SELECT $1 + 1; $$;
+	));
+	for my $function ('bt_index_check', 'bt_index_parent_check')
+	{
+		my $extra = $function eq 'bt_index_check' ? 'false' : 'false, false';
+		my ($ret, $out, $err) = $node->psql('postgres',
+			qq(SELECT $function('idxall_hot_idx', false, $extra, true)));
+		is($ret, 3, "$function rejects mismatched key behind $description");
+		like($err,
+			qr/index tuple in index "idxall_hot_idx" does not match heap tuple/,
+			"$function follows $description to compare keys");
+	}
+	$node->safe_psql('postgres', q(
+		CREATE OR REPLACE FUNCTION idxall_hot_func(int) RETURNS int
+		LANGUAGE sql IMMUTABLE AS $$ SELECT $1; $$;
+	));
+}
diff --git a/contrib/amcheck/verify_nbtree.c b/contrib/amcheck/verify_nbtree.c
index 97c519b47f5..94e43a23e52 100644
--- a/contrib/amcheck/verify_nbtree.c
+++ b/contrib/amcheck/verify_nbtree.c
@@ -13,6 +13,11 @@
  * verify its structure.  A heap scan later uses Bloom filter probes to verify
  * that every visible heap tuple has a matching index tuple.
  *
+ * When index-to-heap verification (indexallkeysmatch) is requested, a Bloom
+ * filter fingerprints (key,tid) from a heap scan first.  The index scan then
+ * probes this filter; when the probe fails, a heap lookup verifies that the
+ * index tuple points to a heap tuple with the same key.
+ *
  *
  * Copyright (c) 2017-2026, PostgreSQL Global Development Group
  *
@@ -30,10 +35,10 @@
 #include "access/tableam.h"
 #include "access/transam.h"
 #include "access/xact.h"
-#include "verify_common.h"
 #include "catalog/index.h"
 #include "catalog/pg_am.h"
 #include "common/pg_prng.h"
+#include "executor/executor.h"
 #include "lib/bloomfilter.h"
 #include "miscadmin.h"
 #include "storage/smgr.h"
@@ -41,6 +46,7 @@
 #include "utils/memutils.h"
 #include "utils/snapmgr.h"
 
+#include "verify_common.h"
 
 PG_MODULE_MAGIC_EXT(
 					.name = "amcheck",
@@ -81,6 +87,8 @@ typedef struct BtreeCheckState
 	bool		readonly;
 	/* Also verifying heap has no unindexed tuples? */
 	bool		heapallindexed;
+	/* Also verifying each index tuple points to heap tuple with same key? */
+	bool		indexallkeysmatch;
 	/* Also making sure non-pivot tuples can be found by new search? */
 	bool		rootdescend;
 	/* Also check uniqueness constraint if index is unique */
@@ -131,6 +139,18 @@ typedef struct BtreeCheckState
 	bloom_filter *filter;
 	/* Debug counter */
 	int64		heaptuplespresent;
+
+	/*
+	 * Mutable state, for optional indexallkeysmatch verification:
+	 */
+
+	/* Bloom filter fingerprints heap (key,tid) pairs */
+	bloom_filter *heapfilter;
+	/* Debug counter for index tuples verified */
+	int64		indextuplesverified;
+	/* Reusable slot and executor state for FormIndexDatum() */
+	TupleTableSlot *iakm_slot;
+	EState	   *iakm_estate;
 } BtreeCheckState;
 
 /*
@@ -168,6 +188,7 @@ typedef struct BTCallbackState
 {
 	bool		parentcheck;
 	bool		heapallindexed;
+	bool		indexallkeysmatch;
 	bool		rootdescend;
 	bool		checkunique;
 } BTCallbackState;
@@ -179,7 +200,7 @@ static void bt_index_check_callback(Relation indrel, Relation heaprel,
 									void *state, bool readonly);
 static void bt_check_every_level(Relation rel, Relation heaprel,
 								 bool heapkeyspace, bool readonly, bool heapallindexed,
-								 bool rootdescend, bool checkunique);
+								 bool indexallkeysmatch, bool rootdescend, bool checkunique);
 static BtreeLevel bt_check_level_from_leftmost(BtreeCheckState *state,
 											   BtreeLevel level);
 static bool bt_leftmost_ignoring_half_dead(BtreeCheckState *state,
@@ -211,6 +232,13 @@ static void bt_downlink_missing_check(BtreeCheckState *state, bool rightsplit,
 static void bt_tuple_present_callback(Relation index, ItemPointer tid,
 									  Datum *values, bool *isnull,
 									  bool tupleIsAlive, void *checkstate);
+static void bt_heap_fingerprint_callback(Relation index, ItemPointer tid,
+										 Datum *values, bool *isnull,
+										 bool tupleIsAlive, void *checkstate);
+static void bt_verify_index_tuple_points_to_heap(BtreeCheckState *state,
+												 IndexTuple itup,
+												 BlockNumber targetblock,
+												 OffsetNumber offset);
 static IndexTuple bt_normalize_tuple(BtreeCheckState *state,
 									 IndexTuple itup);
 static inline IndexTuple bt_posting_plain_tuple(IndexTuple itup, int n);
@@ -239,13 +267,15 @@ static inline ItemPointer BTreeTupleGetHeapTIDCareful(BtreeCheckState *state,
 static inline ItemPointer BTreeTupleGetPointsToTID(IndexTuple itup);
 
 /*
- * bt_index_check(index regclass, heapallindexed boolean, checkunique boolean)
+ * bt_index_check(index regclass, heapallindexed boolean, checkunique boolean, indexallkeysmatch boolean)
  *
  * Verify integrity of B-Tree index.
  *
  * Acquires AccessShareLock on heap & index relations.  Does not consider
  * invariants that exist between parent/child pages.  Optionally verifies
- * that heap does not contain any unindexed or incorrectly indexed tuples.
+ * that heap does not contain any unindexed or incorrectly indexed tuples
+ * (heapallindexed), or that each index tuple points to a heap tuple with
+ * the same key (indexallkeysmatch).
  */
 Datum
 bt_index_check(PG_FUNCTION_ARGS)
@@ -254,6 +284,7 @@ bt_index_check(PG_FUNCTION_ARGS)
 	BTCallbackState args;
 
 	args.heapallindexed = false;
+	args.indexallkeysmatch = false;
 	args.rootdescend = false;
 	args.parentcheck = false;
 	args.checkunique = false;
@@ -262,6 +293,8 @@ bt_index_check(PG_FUNCTION_ARGS)
 		args.heapallindexed = PG_GETARG_BOOL(1);
 	if (PG_NARGS() >= 3)
 		args.checkunique = PG_GETARG_BOOL(2);
+	if (PG_NARGS() >= 4)
+		args.indexallkeysmatch = PG_GETARG_BOOL(3);
 
 	amcheck_lock_relation_and_check(indrelid, BTREE_AM_OID,
 									bt_index_check_callback,
@@ -271,13 +304,15 @@ bt_index_check(PG_FUNCTION_ARGS)
 }
 
 /*
- * bt_index_parent_check(index regclass, heapallindexed boolean, rootdescend boolean, checkunique boolean)
+ * bt_index_parent_check(index regclass, heapallindexed boolean, rootdescend boolean, checkunique boolean, indexallkeysmatch boolean)
  *
  * Verify integrity of B-Tree index.
  *
  * Acquires ShareLock on heap & index relations.  Verifies that downlinks in
  * parent pages are valid lower bounds on child pages.  Optionally verifies
- * that heap does not contain any unindexed or incorrectly indexed tuples.
+ * that heap does not contain any unindexed or incorrectly indexed tuples
+ * (heapallindexed), or that each index tuple points to a heap tuple with
+ * the same key (indexallkeysmatch).
  */
 Datum
 bt_index_parent_check(PG_FUNCTION_ARGS)
@@ -286,6 +321,7 @@ bt_index_parent_check(PG_FUNCTION_ARGS)
 	BTCallbackState args;
 
 	args.heapallindexed = false;
+	args.indexallkeysmatch = false;
 	args.rootdescend = false;
 	args.parentcheck = true;
 	args.checkunique = false;
@@ -296,6 +332,8 @@ bt_index_parent_check(PG_FUNCTION_ARGS)
 		args.rootdescend = PG_GETARG_BOOL(2);
 	if (PG_NARGS() >= 4)
 		args.checkunique = PG_GETARG_BOOL(3);
+	if (PG_NARGS() >= 5)
+		args.indexallkeysmatch = PG_GETARG_BOOL(4);
 
 	amcheck_lock_relation_and_check(indrelid, BTREE_AM_OID,
 									bt_index_check_callback,
@@ -335,7 +373,8 @@ bt_index_check_callback(Relation indrel, Relation heaprel, void *state, bool rea
 
 	/* Check index, possibly against table it is an index on */
 	bt_check_every_level(indrel, heaprel, heapkeyspace, readonly,
-						 args->heapallindexed, args->rootdescend, args->checkunique);
+						 args->heapallindexed, args->indexallkeysmatch,
+						 args->rootdescend, args->checkunique);
 }
 
 /*
@@ -363,8 +402,8 @@ bt_index_check_callback(Relation indrel, Relation heaprel, void *state, bool rea
  */
 static void
 bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace,
-					 bool readonly, bool heapallindexed, bool rootdescend,
-					 bool checkunique)
+					 bool readonly, bool heapallindexed, bool indexallkeysmatch,
+					 bool rootdescend, bool checkunique)
 {
 	BtreeCheckState *state;
 	Page		metapage;
@@ -394,10 +433,41 @@ bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace,
 	state->heapkeyspace = heapkeyspace;
 	state->readonly = readonly;
 	state->heapallindexed = heapallindexed;
+	state->indexallkeysmatch = indexallkeysmatch;
 	state->rootdescend = rootdescend;
 	state->checkunique = checkunique;
 	state->snapshot = InvalidSnapshot;
 
+	if (state->heapallindexed || state->indexallkeysmatch)
+	{
+		/*
+		 * Register our own snapshot for heapallindexed/indexallkeysmatch,
+		 * rather than asking table_index_build_scan() to do this for us
+		 * later.  This needs to happen before fingerprinting begins.
+		 */
+		state->snapshot = RegisterSnapshot(GetTransactionSnapshot());
+
+		/*
+		 * GetTransactionSnapshot() always acquires a new MVCC snapshot in
+		 * READ COMMITTED mode.  A new snapshot is guaranteed to have all the
+		 * entries it requires in the index.
+		 *
+		 * We must defend against the possibility that an old xact snapshot
+		 * was returned at higher isolation levels when that snapshot is not
+		 * safe for index scans of the target index.  This is possible when
+		 * the snapshot sees tuples that are before the index's indcheckxmin
+		 * horizon.  Throwing an error here should be very rare.  It doesn't
+		 * seem worth using a secondary snapshot to avoid this.
+		 */
+		if (IsolationUsesXactSnapshot() && rel->rd_index->indcheckxmin &&
+			!TransactionIdPrecedes(HeapTupleHeaderGetXmin(rel->rd_indextuple->t_data),
+								   state->snapshot->xmin))
+			ereport(ERROR,
+					errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
+					errmsg("index \"%s\" cannot be verified using transaction snapshot",
+						   RelationGetRelationName(rel)));
+	}
+
 	if (state->heapallindexed)
 	{
 		int64		total_pages;
@@ -414,40 +484,36 @@ bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace,
 		total_pages = RelationGetNumberOfBlocks(rel);
 		total_elems = Max(total_pages * (MaxTIDsPerBTreePage / 3),
 						  (int64) state->rel->rd_rel->reltuples);
-		/* Generate a random seed to avoid repetition */
 		seed = pg_prng_uint64(&pg_global_prng_state);
-		/* Create Bloom filter to fingerprint index */
 		state->filter = bloom_create(total_elems, maintenance_work_mem, seed);
 		state->heaptuplespresent = 0;
+	}
+
+	if (state->indexallkeysmatch)
+	{
+		int64		total_pages;
+		int64		total_elems;
+		uint64		seed;
 
 		/*
-		 * Register our own snapshot for heapallindexed, rather than asking
-		 * table_index_build_scan() to do this for us later.  This needs to
-		 * happen before index fingerprinting begins, so we can later be
-		 * certain that index fingerprinting should have reached all tuples
-		 * returned by table_index_build_scan().
+		 * Size Bloom filter based on estimated number of heap tuples.
 		 */
-		state->snapshot = RegisterSnapshot(GetTransactionSnapshot());
+		total_pages = RelationGetNumberOfBlocks(heaprel);
+		total_elems = Max(total_pages * MaxHeapTuplesPerPage,
+						  (int64) heaprel->rd_rel->reltuples);
+		seed = pg_prng_uint64(&pg_global_prng_state);
+		state->heapfilter = bloom_create(total_elems, maintenance_work_mem, seed);
+		state->indextuplesverified = 0;
 
 		/*
-		 * GetTransactionSnapshot() always acquires a new MVCC snapshot in
-		 * READ COMMITTED mode.  A new snapshot is guaranteed to have all the
-		 * entries it requires in the index.
-		 *
-		 * We must defend against the possibility that an old xact snapshot
-		 * was returned at higher isolation levels when that snapshot is not
-		 * safe for index scans of the target index.  This is possible when
-		 * the snapshot sees tuples that are before the index's indcheckxmin
-		 * horizon.  Throwing an error here should be very rare.  It doesn't
-		 * seem worth using a secondary snapshot to avoid this.
+		 * Set up reusable infrastructure for heap lookups by TID: a slot and
+		 * an executor state for FormIndexDatum().  Creating these once per
+		 * verification avoids rebuilding executor state (and recompiling
+		 * index expressions) for every index tuple that misses the Bloom
+		 * filter.
 		 */
-		if (IsolationUsesXactSnapshot() && rel->rd_index->indcheckxmin &&
-			!TransactionIdPrecedes(HeapTupleHeaderGetXmin(rel->rd_indextuple->t_data),
-								   state->snapshot->xmin))
-			ereport(ERROR,
-					errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
-					errmsg("index \"%s\" cannot be verified using transaction snapshot",
-						   RelationGetRelationName(rel)));
+		state->iakm_slot = table_slot_create(heaprel, NULL);
+		state->iakm_estate = CreateExecutorState();
 	}
 
 	/*
@@ -455,11 +521,12 @@ bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace,
 	 * performance, take it once per index check.  If one was already taken
 	 * above, use that.
 	 */
-	if (state->checkunique)
+	if (state->checkunique || state->indexallkeysmatch)
 	{
 		state->indexinfo = BuildIndexInfo(state->rel);
 
-		if (state->indexinfo->ii_Unique && state->snapshot == InvalidSnapshot)
+		if (state->checkunique && state->indexinfo->ii_Unique &&
+			state->snapshot == InvalidSnapshot)
 			state->snapshot = RegisterSnapshot(GetTransactionSnapshot());
 	}
 
@@ -477,6 +544,37 @@ bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace,
 												 ALLOCSET_DEFAULT_SIZES);
 	state->checkstrategy = GetAccessStrategy(BAS_BULKREAD);
 
+	/*
+	 * When indexallkeysmatch, fingerprint heap first so we can verify each
+	 * index tuple points to a heap tuple with the same key during the index
+	 * scan.
+	 */
+	if (state->indexallkeysmatch)
+	{
+		IndexInfo  *indexinfo = BuildIndexInfo(state->rel);
+		TableScanDesc scan;
+
+		scan = table_beginscan_strat(state->heaprel,
+									 state->snapshot,
+									 0, NULL, true, true);
+		indexinfo->ii_Concurrent = true;
+		indexinfo->ii_Unique = false;
+		indexinfo->ii_ExclusionOps = NULL;
+		indexinfo->ii_ExclusionProcs = NULL;
+		indexinfo->ii_ExclusionStrats = NULL;
+
+		elog(DEBUG1, "fingerprinting heap \"%s\" for index \"%s\" verification",
+			 RelationGetRelationName(state->heaprel),
+			 RelationGetRelationName(state->rel));
+
+		table_index_build_scan(state->heaprel, state->rel, indexinfo, true, false,
+							   bt_heap_fingerprint_callback, state, scan);
+
+		ereport(DEBUG1,
+				(errmsg_internal("finished heap fingerprint with bitset %.2f%% set",
+								 100.0 * bloom_prop_bits_set(state->heapfilter))));
+	}
+
 	/* Get true root block from meta-page */
 	metapage = palloc_btree_page(state, BTREE_METAPAGE);
 	metad = BTPageGetMeta(metapage);
@@ -583,6 +681,19 @@ bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace,
 		bloom_free(state->filter);
 	}
 
+	if (state->indexallkeysmatch)
+	{
+		ereport(DEBUG1,
+				(errmsg_internal("finished verifying " INT64_FORMAT " index tuples point to matching heap tuples",
+								 state->indextuplesverified)));
+		bloom_free(state->heapfilter);
+		ExecDropSingleTupleTableSlot(state->iakm_slot);
+		FreeExecutorState(state->iakm_estate);
+		/* These may have been pointing to the now-gone estate */
+		state->indexinfo->ii_ExpressionsState = NIL;
+		state->indexinfo->ii_PredicateState = NULL;
+	}
+
 	/* Be tidy: */
 	if (state->snapshot != InvalidSnapshot)
 		UnregisterSnapshot(state->snapshot);
@@ -1503,6 +1614,30 @@ bt_target_page_check(BtreeCheckState *state)
 			}
 		}
 
+		/* Verify each index tuple points to heap tuple with same key */
+		if (state->indexallkeysmatch && P_ISLEAF(topaque) && !ItemIdIsDead(itemid))
+		{
+			if (BTreeTupleIsPosting(itup))
+			{
+				int			i;
+
+				for (i = 0; i < BTreeTupleGetNPosting(itup); i++)
+				{
+					IndexTuple	logtuple;
+
+					logtuple = bt_posting_plain_tuple(itup, i);
+					bt_verify_index_tuple_points_to_heap(state, logtuple,
+														 state->targetblock, offset);
+					pfree(logtuple);
+				}
+			}
+			else
+			{
+				bt_verify_index_tuple_points_to_heap(state, itup,
+													 state->targetblock, offset);
+			}
+		}
+
 		/*
 		 * * High key check *
 		 *
@@ -2801,6 +2936,131 @@ bt_tuple_present_callback(Relation index, ItemPointer tid, Datum *values,
 		pfree(norm);
 }
 
+/*
+ * Per-tuple callback from table_index_build_scan for indexallkeysmatch.  Add
+ * each visible heap tuple's (key, tid) to the Bloom filter for later probe
+ * during the index scan.
+ */
+static void
+bt_heap_fingerprint_callback(Relation index, ItemPointer tid, Datum *values,
+							 bool *isnull, bool tupleIsAlive, void *checkstate)
+{
+	BtreeCheckState *state = (BtreeCheckState *) checkstate;
+	IndexTuple	itup,
+				norm;
+
+	Assert(state->indexallkeysmatch);
+
+	itup = index_form_tuple(RelationGetDescr(index), values, isnull);
+	itup->t_tid = *tid;
+	norm = bt_normalize_tuple(state, itup);
+	bloom_add_element(state->heapfilter, (unsigned char *) norm,
+					  IndexTupleSize(norm));
+	pfree(itup);
+	if (norm != itup)
+		pfree(norm);
+}
+
+/*
+ * Launched only with indexallkeysmatch:
+ * Verify that the index tuple points to a heap tuple with the same key.
+ * When the Bloom filter lacks the (key, tid), fetch the heap tuple and
+ * compare keys.
+ *
+ * The heap lookup mirrors what a regular index scan does:
+ * table_fetch_tid() with our MVCC snapshot follows LP_REDIRECT and HOT
+ * chains, resolving the TID of the visible tuple version, which we then
+ * load into a slot with table_tuple_fetch_row_version().  A "not found"
+ * result means the tuple is dead or was concurrently pruned; we skip it
+ * exactly as an index scan would.  Here we verify that the visible
+ * heap tuple matches the index key.
+ */
+static void
+bt_verify_index_tuple_points_to_heap(BtreeCheckState *state, IndexTuple itup,
+									 BlockNumber targetblock, OffsetNumber offset)
+{
+	ItemPointer tid = BTreeTupleGetHeapTID(itup);
+	IndexTuple	norm;
+	bool		in_filter;
+
+	Assert(state->indexallkeysmatch);
+
+	norm = bt_normalize_tuple(state, itup);
+	in_filter = !bloom_lacks_element(state->heapfilter, (unsigned char *) norm,
+									 IndexTupleSize(norm));
+	if (norm != itup)
+		pfree(norm);
+
+	if (in_filter)
+	{
+		/* Probably present in the heap fingerprint */
+		state->indextuplesverified++;
+		return;
+	}
+
+	/*
+	 * Bloom filter says (key, tid) not in heap.  Follow TID to verify; this
+	 * amortizes random heap lookups by only fetching when the probe indicates
+	 * absence (Bloom filters have false positives, never false negatives, so
+	 * "not in" means we must verify), or reports corruption when the index
+	 * points to a heap tuple with a different key.
+	 */
+	{
+		TupleTableSlot *slot = state->iakm_slot;
+		IndexTuple	heap_itup;
+		IndexTuple	heap_norm;
+		Datum		values[INDEX_MAX_KEYS];
+		bool		isnull[INDEX_MAX_KEYS];
+		ItemPointerData visibletid;
+
+		/* Reclaim memory from the previous FormIndexDatum() call, if any */
+		ResetPerTupleExprContext(state->iakm_estate);
+
+		/*
+		 * MVCC snapshot holds back the horizon for any tuple it can see, so
+		 * the fetch of the resolved TID should also succeed.
+		 */
+		visibletid = *tid;
+		if (!table_fetch_tid(state->heaprel, &visibletid, state->snapshot, NULL))
+			return;
+
+		if (!table_tuple_fetch_row_version(state->heaprel, &visibletid,
+										   state->snapshot, slot))
+			elog(ERROR, "could not fetch visible tuple (%u,%u) from table \"%s\"",
+				 ItemPointerGetBlockNumber(&visibletid),
+				 ItemPointerGetOffsetNumber(&visibletid),
+				 RelationGetRelationName(state->heaprel));
+
+		GetPerTupleExprContext(state->iakm_estate)->ecxt_scantuple = slot;
+		FormIndexDatum(state->indexinfo, slot, state->iakm_estate,
+					   values, isnull);
+
+		heap_itup = index_form_tuple(RelationGetDescr(state->rel), values, isnull);
+		heap_itup->t_tid = *tid;
+		heap_norm = bt_normalize_tuple(state, heap_itup);
+
+		norm = bt_normalize_tuple(state, itup);
+		if (IndexTupleSize(heap_norm) != IndexTupleSize(norm) ||
+			memcmp(heap_norm, norm, IndexTupleSize(norm)) != 0)
+			ereport(ERROR,
+					(errcode(ERRCODE_INDEX_CORRUPTED),
+					 errmsg("index tuple in index \"%s\" does not match heap tuple in table \"%s\"",
+							RelationGetRelationName(state->rel),
+							RelationGetRelationName(state->heaprel)),
+					 errdetail_internal("Index tid=(%u,%u) points to heap tid=(%u,%u) with different key.",
+										targetblock, offset,
+										ItemPointerGetBlockNumber(tid),
+										ItemPointerGetOffsetNumber(tid))));
+
+		pfree(heap_itup);
+		if (heap_norm != heap_itup)
+			pfree(heap_norm);
+		if (norm != itup)
+			pfree(norm);
+		state->indextuplesverified++;
+	}
+}
+
 /*
  * Normalize an index tuple for fingerprinting.
  *
-- 
2.43.0

From 6906f5461d09a0cf5b1b8e9546fd0a9b0b2fd5ab Mon Sep 17 00:00:00 2001
From: Jakub Wartak <[email protected]>
Date: Thu, 12 Nov 2026 09:29:22 +0100
Subject: [PATCH v16112026 4/7] pg_amcheck: add --indexallkeysmatch option

Author: Andrey Borodin <[email protected]>
Author: Jakub Wartak <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 doc/src/sgml/ref/pg_amcheck.sgml  | 11 +++++
 src/bin/pg_amcheck/pg_amcheck.c   | 67 ++++++++++++++++++++++++-------
 src/bin/pg_amcheck/t/003_check.pl | 25 ++++++++++++
 3 files changed, 89 insertions(+), 14 deletions(-)

diff --git a/doc/src/sgml/ref/pg_amcheck.sgml b/doc/src/sgml/ref/pg_amcheck.sgml
index ef2bdfd19ae..c9f31b678b1 100644
--- a/doc/src/sgml/ref/pg_amcheck.sgml
+++ b/doc/src/sgml/ref/pg_amcheck.sgml
@@ -405,6 +405,17 @@ PostgreSQL documentation
      </listitem>
     </varlistentry>
 
+    <varlistentry>
+     <term><option>--indexallkeysmatch</option></term>
+     <listitem>
+      <para>
+       For each index checked, verify that each index tuple points to a heap
+       tuple with the same key using <xref linkend="amcheck"/>'s
+       <option>indexallkeysmatch</option> option.
+      </para>
+     </listitem>
+    </varlistentry>
+
     <varlistentry>
      <term><option>--parent-check</option></term>
      <listitem>
diff --git a/src/bin/pg_amcheck/pg_amcheck.c b/src/bin/pg_amcheck/pg_amcheck.c
index cced5181cce..61c083f4c89 100644
--- a/src/bin/pg_amcheck/pg_amcheck.c
+++ b/src/bin/pg_amcheck/pg_amcheck.c
@@ -104,6 +104,7 @@ typedef struct AmcheckOptions
 	bool		rootdescend;
 	bool		heapallindexed;
 	bool		checkunique;
+	bool		indexallkeysmatch;
 
 	/* heap and btree hybrid option */
 	bool		no_btree_expansion;
@@ -135,6 +136,7 @@ static AmcheckOptions opts = {
 	.rootdescend = false,
 	.heapallindexed = false,
 	.checkunique = false,
+	.indexallkeysmatch = false,
 	.no_btree_expansion = false
 };
 
@@ -152,6 +154,7 @@ typedef struct DatabaseInfo
 	char	   *datname;
 	char	   *amcheck_schema; /* escaped, quoted literal */
 	bool		is_checkunique;
+	bool		is_indexallkeysmatch;
 } DatabaseInfo;
 
 typedef struct RelationInfo
@@ -271,6 +274,7 @@ main(int argc, char *argv[])
 		{"parent-check", no_argument, NULL, 12},
 		{"install-missing", optional_argument, NULL, 13},
 		{"checkunique", no_argument, NULL, 14},
+		{"indexallkeysmatch", no_argument, NULL, 15},
 
 		{NULL, 0, NULL, 0}
 	};
@@ -441,6 +445,9 @@ main(int argc, char *argv[])
 			case 14:
 				opts.checkunique = true;
 				break;
+			case 15:
+				opts.indexallkeysmatch = true;
+				break;
 			default:
 				/* getopt_long already emitted a complaint */
 				pg_log_error_hint("Try \"%s --help\" for more information.", progname);
@@ -598,12 +605,8 @@ main(int argc, char *argv[])
 		dat->amcheck_schema = PQescapeIdentifier(conn, amcheck_schema,
 												 strlen(amcheck_schema));
 
-		/*
-		 * Check the version of amcheck extension. Skip requested unique
-		 * constraint check with warning if it is not yet supported by
-		 * amcheck.
-		 */
-		if (opts.checkunique == true)
+		/* Verify the version of amcheck extension */
+		if (opts.checkunique || opts.indexallkeysmatch)
 		{
 			/*
 			 * Now amcheck has only major and minor versions in the string but
@@ -620,14 +623,32 @@ main(int argc, char *argv[])
 			/*
 			 * checkunique option is supported in amcheck since version 1.4
 			 */
-			if ((vmaj == 1 && vmin < 4) || vmaj == 0)
+			if (opts.checkunique)
 			{
-				pg_log_warning("option %s is not supported by amcheck version %s",
-							   "--checkunique", amcheck_version);
-				dat->is_checkunique = false;
+				if ((vmaj == 1 && vmin < 4) || vmaj == 0)
+				{
+					pg_log_warning("option %s is not supported by amcheck version %s",
+								   "--checkunique", amcheck_version);
+					dat->is_checkunique = false;
+				}
+				else
+					dat->is_checkunique = true;
+			}
+
+			/*
+			 * indexallkeysmatch option is supported in amcheck since version 1.6
+			 */
+			if (opts.indexallkeysmatch)
+			{
+				if ((vmaj == 1 && vmin < 6) || vmaj == 0)
+				{
+					pg_log_warning("option %s is not supported by amcheck version %s",
+								   "--indexallkeysmatch", amcheck_version);
+					dat->is_indexallkeysmatch = false;
+				}
+				else
+					dat->is_indexallkeysmatch = true;
 			}
-			else
-				dat->is_checkunique = true;
 		}
 
 		PQclear(result);
@@ -881,8 +902,25 @@ prepare_heap_command(PQExpBuffer sql, RelationInfo *rel, PGconn *conn)
 static void
 prepare_btree_command(PQExpBuffer sql, RelationInfo *rel, PGconn *conn)
 {
+	const char *extra_args;
+
 	resetPQExpBuffer(sql);
 
+	/*
+	 * The amcheck functions have no parameter defaults: each added parameter
+	 * came with a new function taking all of the previous ones too.  So
+	 * indexallkeysmatch can only be passed along with an explicit
+	 * checkunique, which every amcheck version supporting the former has.
+	 */
+	if (rel->datinfo->is_indexallkeysmatch)
+		extra_args = rel->datinfo->is_checkunique ?
+			", checkunique := true, indexallkeysmatch := true" :
+			", checkunique := false, indexallkeysmatch := true";
+	else if (rel->datinfo->is_checkunique)
+		extra_args = ", checkunique := true";
+	else
+		extra_args = "";
+
 	if (opts.parent_check)
 		appendPQExpBuffer(sql,
 						  "SELECT %s.bt_index_parent_check("
@@ -896,7 +934,7 @@ prepare_btree_command(PQExpBuffer sql, RelationInfo *rel, PGconn *conn)
 						  rel->datinfo->amcheck_schema,
 						  (opts.heapallindexed ? "true" : "false"),
 						  (opts.rootdescend ? "true" : "false"),
-						  (rel->datinfo->is_checkunique ? ", checkunique := true" : ""),
+						  extra_args,
 						  rel->reloid);
 	else
 		appendPQExpBuffer(sql,
@@ -910,7 +948,7 @@ prepare_btree_command(PQExpBuffer sql, RelationInfo *rel, PGconn *conn)
 						  "AND i.indisready AND i.indisvalid AND i.indislive",
 						  rel->datinfo->amcheck_schema,
 						  (opts.heapallindexed ? "true" : "false"),
-						  (rel->datinfo->is_checkunique ? ", checkunique := true" : ""),
+						  extra_args,
 						  rel->reloid);
 }
 
@@ -1208,6 +1246,7 @@ help(const char *progname)
 	printf(_("\nB-tree index checking options:\n"));
 	printf(_("      --checkunique               check unique constraint if index is unique\n"));
 	printf(_("      --heapallindexed            check that all heap tuples are found within indexes\n"));
+	printf(_("      --indexallkeysmatch         check that all index tuples match their heap tuples\n"));
 	printf(_("      --parent-check              check index parent/child relationships\n"));
 	printf(_("      --rootdescend               search from root page to refind tuples\n"));
 	printf(_("\nConnection options:\n"));
diff --git a/src/bin/pg_amcheck/t/003_check.pl b/src/bin/pg_amcheck/t/003_check.pl
index ee714c3fc8f..1c9cec977de 100644
--- a/src/bin/pg_amcheck/t/003_check.pl
+++ b/src/bin/pg_amcheck/t/003_check.pl
@@ -604,6 +604,19 @@ $node->command_checks_all(
 	[$no_output_re],
 	'pg_amcheck smoke test --heapallindexed --rootdescend --checkunique');
 
+$node->command_checks_all(
+	[
+		@cmd,
+		'--schema' => 's1',
+		'--index' => 't1_btree',
+		'--heapallindexed',
+		'--rootdescend', '--checkunique', '--indexallkeysmatch', 'db1'
+	],
+	2,
+	[$index_missing_relation_fork_re],
+	[$no_output_re],
+	'pg_amcheck smoke test --heapallindexed --rootdescend --checkunique --indexallkeysmatch');
+
 $node->command_checks_all(
 	[
 		@cmd,
@@ -635,4 +648,16 @@ $node->command_checks_all(
 		qr/pg_amcheck: warning: option --checkunique is not supported by amcheck version 1.3/
 	],
 	'pg_amcheck smoke test --checkunique');
+
+#
+# Same for the indexallkeysmatch option for not supported versions.
+#
+$node->command_checks_all(
+	[ @cmd, '--indexallkeysmatch', '--parent-check', 'db3' ],
+	0,
+	[$no_output_re],
+	[
+		qr/pg_amcheck: warning: option --indexallkeysmatch is not supported by amcheck version 1.3/
+	],
+	'pg_amcheck smoke test --indexallkeysmatch --parent-check');
 done_testing();
-- 
2.43.0

From 8c4a9b52cc6c58d82260617a1e134f8069a22fec Mon Sep 17 00:00:00 2001
From: Jakub Wartak <[email protected]>
Date: Thu, 12 Nov 2026 10:06:08 +0100
Subject: [PATCH v16112026 5/7] amcheck: verify against dangling btree pointers
 to HOT tuples too

Author: Andrey Borodin <[email protected]>
Author: Jakub Wartak <[email protected]>
Discussion: https://postgr.es/m/[email protected]
---
 contrib/amcheck/verify_nbtree.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/contrib/amcheck/verify_nbtree.c b/contrib/amcheck/verify_nbtree.c
index 59516bde6e6..91c24f121df 100644
--- a/contrib/amcheck/verify_nbtree.c
+++ b/contrib/amcheck/verify_nbtree.c
@@ -3219,6 +3219,21 @@ bt_report_dangling_index_entry(BtreeCheckState *state, ItemPointer tid,
 									targetblock, offset,
 									blkno, offnum)));
 
+	/*
+	 * Valid btree tuple should never point directly to a HOT tuple (HOT
+	 * should be only reached by chain).
+	 */
+	if (ItemIdIsNormal(lp) &&
+		HeapTupleHeaderIsHeapOnly((HeapTupleHeader) PageGetItem(page, lp)))
+		ereport(ERROR,
+				(errcode(ERRCODE_INDEX_CORRUPTED),
+				 errmsg("index tuple in index \"%s\" points to heap-only tuple in table \"%s\"",
+						RelationGetRelationName(state->rel),
+						RelationGetRelationName(state->heaprel)),
+				 errdetail_internal("Index tid=(%u,%u) points to heap tid=(%u,%u), which is not the root of a HOT chain.",
+									targetblock, offset,
+									blkno, offnum)));
+
 	/* LP_DEAD, LP_REDIRECT or a dead LP_NORMAL tuple: not corruption */
 	UnlockReleaseBuffer(buffer);
 }
-- 
2.43.0

From 2e0f7a2285e0620ea3d4ef059f212e238c4eb700 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <[email protected]>
Date: Thu, 12 Nov 2026 10:22:06 +0100
Subject: [PATCH v16112026 6/7] mention github action runners/CI

---
 contrib/amcheck/t/008_verify_nbtree_lost_segments.pl | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/contrib/amcheck/t/008_verify_nbtree_lost_segments.pl b/contrib/amcheck/t/008_verify_nbtree_lost_segments.pl
index 16b44b05041..fec37801eed 100644
--- a/contrib/amcheck/t/008_verify_nbtree_lost_segments.pl
+++ b/contrib/amcheck/t/008_verify_nbtree_lost_segments.pl
@@ -33,6 +33,8 @@ my ($result, $stdout, $stderr);
 # The test tables are small, so a second relation segment only exists when
 # the server was built with a tiny segment size (--with-segsize-blocks).
 # There is no way to simulate a lost segment otherwise; skip in that case.
+# During the CI at least one runner should be used with such setup (see
+# .github/workflows/pg-ci.yml)
 my $segpath1 = relation_filepath('missingsegs_test1') . ".1";
 my $segpath2 = relation_filepath('missingsegs_test2') . ".1";
 if (!-e $segpath1 || !-e $segpath2)
-- 
2.43.0

From e184253695e8187c8faed70df04fa2447dfa7793 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <[email protected]>
Date: Mon, 16 Nov 2026 12:04:13 +0100
Subject: [PATCH v16112026 7/7] verify_heapam: make beyond-EOF TID check heapAM
 only

---
 contrib/amcheck/verify_nbtree.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)

diff --git a/contrib/amcheck/verify_nbtree.c b/contrib/amcheck/verify_nbtree.c
index 91c24f121df..da9b926afad 100644
--- a/contrib/amcheck/verify_nbtree.c
+++ b/contrib/amcheck/verify_nbtree.c
@@ -441,12 +441,13 @@ bt_check_every_level(Relation rel, Relation heaprel, bool heapkeyspace,
 
 	/*
 	 * Remember the current size of the heap for beyond-EOF TID checks.  When
-	 * the main fork is missing entirely, skip those checks (by making any
-	 * comparison against heapnblocks false): the user may have deliberately
-	 * excluded the corrupt table from table-level verification, which is what
-	 * reports a missing main fork.
+	 * the main fork is not heapAM or the main fork is missing entirely, skip
+	 * those checks (by making any comparison against heapnblocks false): the
+	 * user may have deliberately excluded the corrupt table from table-level
+	 * verification, which is what reports a missing main fork.
 	 */
-	if (smgrexists(RelationGetSmgr(state->heaprel), MAIN_FORKNUM))
+	if (state->heaprel->rd_rel->relam == HEAP_TABLE_AM_OID &&
+		smgrexists(RelationGetSmgr(state->heaprel), MAIN_FORKNUM))
 		state->heapnblocks = RelationGetNumberOfBlocks(state->heaprel);
 	else
 		state->heapnblocks = InvalidBlockNumber;
-- 
2.43.0

Reply via email to