From d78c6eb901cfc7200bdccf602aff598bb0c5861f Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
Date: Sat, 5 Dec 2026 20:35:57 -0500
Subject: [PATCH v1 2/2] Log a snapshot conflict when BRIN summarization omits
 dead tuples

Summarizing a page range of a BRIN index leaves out the heap tuples
that are dead on the primary, so the new summary may not cover them.
The tuples stay in the heap, and nothing told a standby about it.  With
hot_standby_feedback off, a snapshot there can still see such a tuple,
and it missed the row when it used the index.

Other index AMs handle this with a snapshot conflict horizon.  When
nbtree and hash delete index tuples that point to dead heap tuples,
which are still in the heap, their WAL records (xl_btree_delete,
xl_hash_vacuum_one_page) carry a horizon computed from those heap
tuples, and replay resolves the conflict with the snapshots that might
still see them.  nbtree's xl_btree_reuse_page exists only to generate
such a conflict.

Do the same for BRIN.  The heap scan remembers the newest XID that
deleted a dead tuple it left out, in the new IndexInfo field
ii_DeadTuplesHorizon.  summarize_range() logs it in a new record,
XLOG_BRIN_SUMMARIZE_CONFLICT, before it replaces the placeholder tuple
with the summary.  Replaying that record waits for the conflicting
snapshots, up to max_standby_streaming_delay, and then cancels them.

Caveats:

* This is a prototype.  It adds a WAL record type without bumping
  XLOG_PAGE_MAGIC, and the documentation of recovery conflicts is not
  updated.

* The conflict is coarse.  It hits every snapshot in the database that
  is older than the newest deleting transaction, even if the dead
  tuples did not make the summary any narrower.  Telling that would
  take the values of the dead tuples, and their TOAST data may be gone.

* Only summarization is covered.  CREATE INDEX and REINDEX also leave
  out dead tuples, for every index type, and are not changed.

* VACUUM, brin_summarize_new_values() and autosummarization go through
  summarize_range() as well, but only brin_summarize_range() is tested.

The reproducer added by the previous commit expected the snapshot to
find the row after the standby had replayed the summarization.  Now the
standby does not get that far while the snapshot exists, so adapt the
test.  The standby waits for conflicting snapshots without a limit, and
the test checks that the replay waits, that the snapshot still finds
the row, and that a new snapshot gets correct results once the replay
has continued.
---
 src/backend/access/brin/README                | 10 ++++++
 src/backend/access/brin/brin.c                | 26 ++++++++++++++++
 src/backend/access/brin/brin_xlog.c           | 22 +++++++++++++
 src/backend/access/heap/heapam_handler.c      | 14 ++++++++-
 src/backend/access/rmgrdesc/brindesc.c        | 13 ++++++++
 src/backend/catalog/index.c                   |  1 +
 src/backend/catalog/toasting.c                |  1 +
 src/backend/nodes/makefuncs.c                 |  2 ++
 src/include/access/brin_xlog.h                | 20 ++++++++++++
 src/include/access/tableam.h                  |  6 ++--
 src/include/nodes/execnodes.h                 |  8 +++--
 .../t/068_brin_summarize_standby_snapshot.pl  | 31 ++++++++++++++-----
 src/tools/pgindent/typedefs.list              |  1 +
 13 files changed, 142 insertions(+), 13 deletions(-)

diff --git a/src/backend/access/brin/README b/src/backend/access/brin/README
index 636d96545b2..70342a64c98 100644
--- a/src/backend/access/brin/README
+++ b/src/backend/access/brin/README
@@ -132,6 +132,16 @@ brin_summarize_new_values().  Both these procedures scan all the
 unsummarized ranges, and create a summary tuple.  Again, this includes the
 partially-filled page range at the end of the table.
 
+Summarization leaves out the heap tuples that are dead to all snapshots on
+the server, so the summary might not cover them.  A snapshot on a standby
+that does not report its xmin might still see such a tuple, and must not use
+that summary.  The tuples are not removed from the heap, so nothing else
+would tell the standby.  Therefore the summarization WAL-logs the newest XID
+that deleted such a tuple before it installs the summary.  Replaying that
+record resolves the conflict with the snapshots that might still see the
+tuples, the same way as replaying the deletion of index tuples in nbtree or
+hash does.
+
 Vacuuming
 ---------
 
diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index 5fc40845c17..f2a8b7938ab 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -1822,10 +1822,36 @@ summarize_range(IndexInfo *indexInfo, BrinBuildState *state, Relation heapRel,
 	 * cases.
 	 */
 	state->bs_currRangeStart = heapBlk;
+	indexInfo->ii_DeadTuplesHorizon = InvalidTransactionId;
 	table_index_build_range_scan(heapRel, state->bs_irel, indexInfo, false, true, false,
 								 heapBlk, scanNumBlks,
 								 brinbuildCallback, state, NULL);
 
+	/*
+	 * The scan left out the heap tuples that are dead to every snapshot on
+	 * this server, so the summary we are about to install might not cover
+	 * them.  A snapshot on a standby could still see such a tuple, and it
+	 * must not use the new summary.  The tuples stay in the heap, so no other
+	 * WAL record makes the standby resolve that conflict.  Log a snapshot
+	 * conflict horizon of our own, before the record that replaces the
+	 * placeholder tuple.  nbtree and hash do the same when they delete index
+	 * tuples that point to dead heap tuples (see xl_btree_delete and
+	 * xl_hash_vacuum_one_page).
+	 */
+	if (TransactionIdIsValid(indexInfo->ii_DeadTuplesHorizon) &&
+		RelationNeedsWAL(state->bs_irel) && XLogStandbyInfoActive())
+	{
+		xl_brin_summarize_conflict xlrec;
+
+		xlrec.locator = heapRel->rd_locator;
+		xlrec.snapshotConflictHorizon = indexInfo->ii_DeadTuplesHorizon;
+		xlrec.isCatalogRel = RelationIsAccessibleInLogicalDecoding(heapRel);
+
+		XLogBeginInsert();
+		XLogRegisterData(&xlrec, SizeOfBrinSummarizeConflict);
+		XLogInsert(RM_BRIN_ID, XLOG_BRIN_SUMMARIZE_CONFLICT);
+	}
+
 	/*
 	 * Now we update the values obtained by the scan with the placeholder
 	 * tuple.  We do this in a loop which only terminates if we're able to
diff --git a/src/backend/access/brin/brin_xlog.c b/src/backend/access/brin/brin_xlog.c
index 0b598633912..8823fdc056a 100644
--- a/src/backend/access/brin/brin_xlog.c
+++ b/src/backend/access/brin/brin_xlog.c
@@ -15,6 +15,7 @@
 #include "access/brin_xlog.h"
 #include "access/bufmask.h"
 #include "access/xlogutils.h"
+#include "storage/standby.h"
 
 
 /*
@@ -305,6 +306,24 @@ brin_xlog_desummarize_page(XLogReaderState *record)
 		UnlockReleaseBuffer(buffer);
 }
 
+static void
+brin_xlog_summarize_conflict(XLogReaderState *record)
+{
+	xl_brin_summarize_conflict *xlrec;
+
+	xlrec = (xl_brin_summarize_conflict *) XLogRecGetData(record);
+
+	/*
+	 * The record that follows installs a summary which might not cover heap
+	 * tuples that a snapshot on this standby still sees.  Those snapshots
+	 * have to be gone before we replay it.
+	 */
+	if (InHotStandby)
+		ResolveRecoveryConflictWithSnapshot(xlrec->snapshotConflictHorizon,
+											xlrec->isCatalogRel,
+											xlrec->locator);
+}
+
 void
 brin_redo(XLogReaderState *record)
 {
@@ -330,6 +349,9 @@ brin_redo(XLogReaderState *record)
 		case XLOG_BRIN_DESUMMARIZE:
 			brin_xlog_desummarize_page(record);
 			break;
+		case XLOG_BRIN_SUMMARIZE_CONFLICT:
+			brin_xlog_summarize_conflict(record);
+			break;
 		default:
 			elog(PANIC, "brin_redo: unknown op code %u", info);
 	}
diff --git a/src/backend/access/heap/heapam_handler.c b/src/backend/access/heap/heapam_handler.c
index 1437274b0c6..86d4e953044 100644
--- a/src/backend/access/heap/heapam_handler.c
+++ b/src/backend/access/heap/heapam_handler.c
@@ -21,6 +21,7 @@
 
 #include "access/genam.h"
 #include "access/heapam.h"
+#include "access/heapam_xlog.h"
 #include "access/heaptoast.h"
 #include "access/multixact.h"
 #include "access/rewriteheap.h"
@@ -1379,7 +1380,18 @@ heapam_index_build_range_scan(Relation heapRelation,
 											 hscan->rs_cbuf))
 			{
 				case HEAPTUPLE_DEAD:
-					/* Definitely dead, we can ignore it */
+
+					/*
+					 * Definitely dead, we can ignore it.  But remember the
+					 * newest XID that deleted such a tuple.  A snapshot on a
+					 * standby might still see the tuple, if the standby does
+					 * not report its xmin to us.  A caller that must not
+					 * leave out such a tuple without telling the standby,
+					 * such as the summarization of a BRIN page range, logs
+					 * the XID as a snapshot conflict horizon.
+					 */
+					HeapTupleHeaderAdvanceConflictHorizon(heapTuple->t_data,
+														  &indexInfo->ii_DeadTuplesHorizon);
 					indexIt = false;
 					tupleIsAlive = false;
 					break;
diff --git a/src/backend/access/rmgrdesc/brindesc.c b/src/backend/access/rmgrdesc/brindesc.c
index 618d8a417f6..b867f1cfcec 100644
--- a/src/backend/access/rmgrdesc/brindesc.c
+++ b/src/backend/access/rmgrdesc/brindesc.c
@@ -68,6 +68,16 @@ brin_desc(StringInfo buf, XLogReaderState *record)
 		appendStringInfo(buf, "pagesPerRange %u, heapBlk %u, page offset %u",
 						 xlrec->pagesPerRange, xlrec->heapBlk, xlrec->regOffset);
 	}
+	else if (info == XLOG_BRIN_SUMMARIZE_CONFLICT)
+	{
+		xl_brin_summarize_conflict *xlrec = (xl_brin_summarize_conflict *) rec;
+
+		appendStringInfo(buf, "rel %u/%u/%u, snapshotConflictHorizon: %u, isCatalogRel: %c",
+						 xlrec->locator.spcOid, xlrec->locator.dbOid,
+						 xlrec->locator.relNumber,
+						 xlrec->snapshotConflictHorizon,
+						 xlrec->isCatalogRel ? 'T' : 'F');
+	}
 }
 
 const char *
@@ -101,6 +111,9 @@ brin_identify(uint8 info)
 		case XLOG_BRIN_DESUMMARIZE:
 			id = "DESUMMARIZE";
 			break;
+		case XLOG_BRIN_SUMMARIZE_CONFLICT:
+			id = "SUMMARIZE_CONFLICT";
+			break;
 	}
 
 	return id;
diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c
index 99413556572..a6f430f9daa 100644
--- a/src/backend/catalog/index.c
+++ b/src/backend/catalog/index.c
@@ -1553,6 +1553,7 @@ index_concurrently_build(Oid heapRelationId,
 	Assert(!indexInfo->ii_ReadyForInserts);
 	indexInfo->ii_Concurrent = true;
 	indexInfo->ii_BrokenHotChain = false;
+	indexInfo->ii_DeadTuplesHorizon = InvalidTransactionId;
 
 	/* Now build the index */
 	index_build(heapRel, indexRelation, indexInfo, false, true, true);
diff --git a/src/backend/catalog/toasting.c b/src/backend/catalog/toasting.c
index 3058ec14223..a270ae01984 100644
--- a/src/backend/catalog/toasting.c
+++ b/src/backend/catalog/toasting.c
@@ -363,6 +363,7 @@ create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
 	indexInfo->ii_IndexUnchanged = false;
 	indexInfo->ii_Concurrent = false;
 	indexInfo->ii_BrokenHotChain = false;
+	indexInfo->ii_DeadTuplesHorizon = InvalidTransactionId;
 	indexInfo->ii_ParallelWorkers = 0;
 	indexInfo->ii_Am = BTREE_AM_OID;
 	indexInfo->ii_AmCache = NULL;
diff --git a/src/backend/nodes/makefuncs.c b/src/backend/nodes/makefuncs.c
index cdc02b274ff..5ebc06955ea 100644
--- a/src/backend/nodes/makefuncs.c
+++ b/src/backend/nodes/makefuncs.c
@@ -15,6 +15,7 @@
  */
 #include "postgres.h"
 
+#include "access/transam.h"
 #include "catalog/pg_class.h"
 #include "catalog/pg_type.h"
 #include "nodes/makefuncs.h"
@@ -874,6 +875,7 @@ makeIndexInfo(int numattrs, int numkeyattrs, Oid amoid, List *expressions,
 
 	/* initialize index-build state to default */
 	n->ii_BrokenHotChain = false;
+	n->ii_DeadTuplesHorizon = InvalidTransactionId;
 	n->ii_ParallelWorkers = 0;
 
 	/* set up for possible use by index AM */
diff --git a/src/include/access/brin_xlog.h b/src/include/access/brin_xlog.h
index 1c60dc8adb9..35d4aacf5b3 100644
--- a/src/include/access/brin_xlog.h
+++ b/src/include/access/brin_xlog.h
@@ -34,6 +34,7 @@
 #define XLOG_BRIN_SAMEPAGE_UPDATE	0x30
 #define XLOG_BRIN_REVMAP_EXTEND		0x40
 #define XLOG_BRIN_DESUMMARIZE		0x50
+#define XLOG_BRIN_SUMMARIZE_CONFLICT	0x60
 
 #define XLOG_BRIN_OPMASK			0x70
 /*
@@ -142,6 +143,25 @@ typedef struct xl_brin_desummarize
 #define SizeOfBrinDesummarize	(offsetof(xl_brin_desummarize, regOffset) + \
 								 sizeof(OffsetNumber))
 
+/*
+ * This is what we need to know about the dead heap tuples that the
+ * summarization of a page range left out.  This record only exists to
+ * generate a conflict point for Hot Standby, like xl_btree_reuse_page.
+ *
+ * Note that we must include the RelFileLocator of the table in the record,
+ * because no buffer is registered with it.
+ */
+typedef struct xl_brin_summarize_conflict
+{
+	RelFileLocator locator;
+	TransactionId snapshotConflictHorizon;
+	bool		isCatalogRel;	/* to handle recovery conflict during logical
+								 * decoding on standby */
+} xl_brin_summarize_conflict;
+
+#define SizeOfBrinSummarizeConflict	(offsetof(xl_brin_summarize_conflict, isCatalogRel) + \
+									 sizeof(bool))
+
 
 extern void brin_redo(XLogReaderState *record);
 extern void brin_desc(StringInfo buf, XLogReaderState *record);
diff --git a/src/include/access/tableam.h b/src/include/access/tableam.h
index 9d2fc7f9acb..9741be1bfad 100644
--- a/src/include/access/tableam.h
+++ b/src/include/access/tableam.h
@@ -1860,8 +1860,10 @@ table_scan_analyze_next_tuple(TableScanDesc scan,
  * any potentially broken HOT chains.  Currently, we set this if there are any
  * RECENTLY_DEAD or DELETE_IN_PROGRESS entries in a HOT chain, without trying
  * very hard to detect whether they're really incompatible with the chain tip.
- * This only really makes sense for heap AM, it might need to be generalized
- * for other AMs later.
+ * Another side effect is to advance indexInfo->ii_DeadTuplesHorizon to the
+ * newest XID that deleted a DEAD tuple, which the scan leaves out.  This only
+ * really makes sense for heap AM, it might need to be generalized for other
+ * AMs later.
  */
 static inline double
 table_index_build_scan(Relation table_rel,
diff --git a/src/include/nodes/execnodes.h b/src/include/nodes/execnodes.h
index e4fd53c383b..602231f4bc7 100644
--- a/src/include/nodes/execnodes.h
+++ b/src/include/nodes/execnodes.h
@@ -168,8 +168,10 @@ typedef struct ExprState
  *		entries for a particular index.  Used for both index_build and
  *		retail creation of index entries.
  *
- * ii_Concurrent, ii_BrokenHotChain, and ii_ParallelWorkers are used only
- * during index build; they're conventionally zeroed otherwise.
+ * ii_Concurrent, ii_BrokenHotChain, ii_DeadTuplesHorizon, and
+ * ii_ParallelWorkers are used only during index build; they're conventionally
+ * zeroed otherwise.  ii_DeadTuplesHorizon is not collected from the workers
+ * of a parallel build.
  * ----------------
  */
 typedef struct IndexInfo
@@ -223,6 +225,8 @@ typedef struct IndexInfo
 	bool		ii_Concurrent;
 	/* did we detect any broken HOT chains? */
 	bool		ii_BrokenHotChain;
+	/* newest XID that deleted a dead tuple the build scan left out, if any */
+	TransactionId ii_DeadTuplesHorizon;
 	/* is it a summarizing index? */
 	bool		ii_Summarizing;
 	/* is it a WITHOUT OVERLAPS index? */
diff --git a/src/test/recovery/t/068_brin_summarize_standby_snapshot.pl b/src/test/recovery/t/068_brin_summarize_standby_snapshot.pl
index 70d506942c4..f4c9f6b814a 100644
--- a/src/test/recovery/t/068_brin_summarize_standby_snapshot.pl
+++ b/src/test/recovery/t/068_brin_summarize_standby_snapshot.pl
@@ -2,13 +2,14 @@
 # Copyright (c) 2026, PostgreSQL Global Development Group
 
 # Test that a snapshot on a standby gets correct results through a BRIN index
-# after a page range was summarized again on the primary.
+# when a page range is summarized again on the primary.
 #
 # Summarizing a page range leaves out the row versions that are dead on the
 # primary.  With hot_standby_feedback off, the primary does not know about
 # the snapshots on a standby, and one of them might still see such a row
 # version.  The summarization does not remove the row version from the table,
-# so replaying it does not conflict with that snapshot.
+# so it logs a snapshot conflict horizon of its own, and the standby must not
+# replay the new summary while such a snapshot exists.
 use strict;
 use warnings FATAL => 'all';
 
@@ -36,6 +37,10 @@ $primary->backup('backup');
 my $standby = PostgreSQL::Test::Cluster->new('standby');
 $standby->init_from_backup($primary, 'backup', has_streaming => 1);
 $standby->append_conf('postgresql.conf', 'hot_standby_feedback = off');
+
+# Make the replay wait for a conflicting snapshot, instead of cancelling its
+# query after a while.
+$standby->append_conf('postgresql.conf', 'max_standby_streaming_delay = -1');
 $standby->start;
 
 # Take a snapshot on the standby.  This session has no choice but the index,
@@ -62,16 +67,26 @@ is( $primary->safe_psql(
 	'1',
 	'the page range is summarized again');
 
-# The summarization does not commit a transaction that has an XID, so its
-# WAL records are not flushed right away.  Wait until the standby has
-# replayed all the WAL inserted so far, not just what was written out.
-$primary->wait_for_catchup($standby, 'replay', $primary->lsn('insert'));
-
-# The standby snapshot still sees the deleted row.
+# The standby must not replay the new summary while the snapshot exists, so
+# the replay has to wait.  The snapshot still sees the deleted row.
+$standby->wait_for_event('startup', 'RecoveryConflictSnapshot');
 is($reader->query_safe(q{SELECT k FROM tab WHERE k = 1}), '1',
 	'standby snapshot finds a row deleted before the range was summarized again'
 );
+
+# The replay continues once the snapshot is gone.  The summarization does
+# not commit a transaction that has an XID, so its WAL records are not
+# flushed right away; wait for all the WAL inserted so far, not just for
+# what was written out.
 $reader->query_safe('COMMIT');
+$primary->wait_for_catchup($standby, 'replay', $primary->lsn('insert'));
+
+# A snapshot taken now does not see the deleted row, and it gets correct
+# results with the new summary.
+is($reader->query_safe(q{SELECT k FROM tab WHERE k = 1}),
+	'', 'new standby snapshot does not find the deleted row');
+is($reader->query_safe(q{SELECT k FROM tab WHERE k = 5}),
+	'5', 'new standby snapshot finds the other row through the index');
 $reader->quit;
 
 done_testing();
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index 278b2f3194b..5c066ab5443 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -4457,6 +4457,7 @@ xl_brin_desummarize
 xl_brin_insert
 xl_brin_revmap_extend
 xl_brin_samepage_update
+xl_brin_summarize_conflict
 xl_brin_update
 xl_btree_dedup
 xl_btree_delete
-- 
2.56.1

