From 4a1f305687d11ec2aa238b0dcb8ac1381c886c84 Mon Sep 17 00:00:00 2001
From: Evgeny Voropaev <evorop@gmail.com>
Date: Fri, 4 Apr 2025 14:10:16 +0800
Subject: [PATCH] Fixing page inconsistency with a single tuple on the page.

Added a condition checking weither a page was really empty or not. The condition was added into the logic deciding
 on the matter of INSERT+INT xlog record type on the DO side.

---
 src/backend/access/heap/heapam.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c
index 6ac653833fa..8e671857dce 100644
--- a/src/backend/access/heap/heapam.c
+++ b/src/backend/access/heap/heapam.c
@@ -2145,6 +2145,8 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid,
 	Buffer		buffer;
 	Buffer		vmbuffer = InvalidBuffer;
 	bool		all_visible_cleared = false;
+	PageHeader	pageheader;
+	bool		were_not_tuples;
 
 	/* Cheap, simplistic check that the tuple matches the rel's rowtype. */
 	Assert(HeapTupleHeaderGetNatts(tup->t_data) <=
@@ -2190,6 +2192,9 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid,
 	/* NO EREPORT(ERROR) from here till changes are logged */
 	START_CRIT_SECTION();
 
+	pageheader = (PageHeader) BufferGetPage(buffer);
+	were_not_tuples = pageheader->pd_special == (uint32) pageheader->pd_upper;
+
 	RelationPutHeapTuple(relation, buffer, heaptup,
 						 (options & HEAP_INSERT_SPECULATIVE) != 0);
 
@@ -2240,7 +2245,7 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid,
 		 * buffer references from XLogInsert.
 		 */
 		if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
-			PageGetMaxOffsetNumber(page) == FirstOffsetNumber)
+			PageGetMaxOffsetNumber(page) == FirstOffsetNumber && were_not_tuples)
 		{
 			info |= XLOG_HEAP_INIT_PAGE;
 			bufflags |= REGBUF_WILL_INIT;
-- 
2.49.0

