From 8784e123f8385fa1e55ce9e080a0676e03757691 Mon Sep 17 00:00:00 2001
From: Jakub Wartak <jakub.wartak@enterprisedb.com>
Date: Wed, 18 Nov 2026 09:15:41 +0100
Subject: [PATCH v18112026 8/9] amcheck: validate heap TIDs before calling any
 ItemPointerGetBlockNumber()

Any call to ItemPointerGetBlockNumber() within bt_target_page_check() on
zeroed heap TID (ip_posid) could cause end up with trap failures due to
"ItemPointerIsValid(pointer)". Harden the checks to discover such cases
earlier even in non-assert enabled builds.

Author: Andrey Borodin <amborodin@acm.org>
Author: Jakub Wartak <jakub.wartak@enterprisedb.com>
Discussion: https://postgr.es/m/432626F9-65DF-4F0D-B345-26CFC3E2CFAC@yandex-team.ru
---
 contrib/amcheck/verify_nbtree.c | 43 ++++++++++++++++++++++++++++++++-
 1 file changed, 42 insertions(+), 1 deletion(-)

diff --git a/contrib/amcheck/verify_nbtree.c b/contrib/amcheck/verify_nbtree.c
index da9b926afad..55607dcf60a 100644
--- a/contrib/amcheck/verify_nbtree.c
+++ b/contrib/amcheck/verify_nbtree.c
@@ -1469,6 +1469,46 @@ bt_target_page_check(BtreeCheckState *state)
 										LSN_FORMAT_ARGS(state->targetlsn))));
 		}
 
+		/*
+		 * Heap TIDs stored in the leaf page tuples must be valid item
+		 * pointers regardless of the the table AM implementation.
+		 */
+		if (P_ISLEAF(topaque) && !BTreeTupleIsPivot(itup))
+		{
+			int			nhtids = 1;
+
+			if (BTreeTupleIsPosting(itup))
+				nhtids = BTreeTupleGetNPosting(itup);
+
+			for (int i = 0; i < nhtids; i++)
+			{
+				ItemPointer htid;
+				char	   *postingoff = "";
+
+				if (BTreeTupleIsPosting(itup))
+					htid = BTreeTupleGetPostingN(itup, i);
+				else
+					htid = &itup->t_tid;
+
+				/* Valid heap TID cannot be zero */
+				if (ItemPointerIsValid(htid))
+					continue;
+
+				if (BTreeTupleIsPosting(itup))
+					postingoff = psprintf(" posting list offset=%d", i);
+
+				ereport(ERROR,
+						(errcode(ERRCODE_INDEX_CORRUPTED),
+						 errmsg("index tuple in index \"%s\" contains invalid heap TID",
+								RelationGetRelationName(state->rel)),
+						 errdetail_internal("Index tid=(%u,%u)%s points to heap tid=(%u,%u) page lsn=%X/%08X.",
+											state->targetblock, offset, postingoff,
+											ItemPointerGetBlockNumberNoCheck(htid),
+											ItemPointerGetOffsetNumberNoCheck(htid),
+											LSN_FORMAT_ARGS(state->targetlsn))));
+			}
+		}
+
 		/*
 		 * Don't try to generate scankey using "negative infinity" item on
 		 * internal pages. They are always truncated to zero attributes.
@@ -3198,7 +3238,8 @@ bt_report_dangling_index_entry(BtreeCheckState *state, ItemPointer tid,
 	LockBuffer(buffer, BUFFER_LOCK_SHARE);
 	page = BufferGetPage(buffer);
 
-	if (offnum > PageGetMaxOffsetNumber(page))
+	if (offnum < FirstOffsetNumber ||
+		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",
-- 
2.43.0

