Hi,

While investigating some issues related to BRIN, I found three
long-standing bugs in the summarization. The bugs are separate, but
small enough and related to the same are of code, so I'm submitting them
together. Each bug has a TAP test reproducing it, followed by a fix.


1) Desummarization could deadlock with a summary update

An update moving a summary to another page locks the regular page first,
and then locks the revmap page (to publish the new location). But the
brin_desummarize_page() acquires the locks in the opposite order (holds
the revmap lock while waiting for the regular page). That means a risk
of a deadlock, and it's enough if the summaries share a page.

Moreover, those are buffer content locks - the deadlock detector does
not handle those, so this deadlock is indefinite.

The fix changes the desummarization to retry. It copies the summary's
location under a shared revmap lock, and releases that lock. It then
locks the regular page before re-locking revmap, and rechecking if it's
still pointing to the expected block/offset, and retrying if not.

(I wonder if this needs some protection against indefinite retries.)


2) infinite loop after interrupting evacuation

The evacumation marks the page as BRIN_EVACUATE_PAGE. If the evacuation
gets interrupted in some way, we may end up with a page with the flag
bug still containing live summaries. This causes infinite loop, because
brininsert considers just size for in-place updates. But brin_doupdate
rejects the update because of the flag. It retries pretty much forever
(maybe the evacuation could complete and break the loop?). Anyway, it's
effectively a livelock.

To fix, both decisions can use brin_can_do_samepage_update, which checks
the flag under a buffer lock. A marked page is ineligible even for a
same-size replacement, so that the summary gets moved elsewhere.


3) index extension could initialize a new page without a lock

An update moving a summary may extend the index, and then realize the
page has already been added to the revmap. Before retrying,
brin_getinsertbuffer initializes the unused page as an empty regular
page so its free space could be reused. But it only holds a pin, not an
exclusive (content) lock needed for that. This triggers an assert in
MarkBufferDirty (without assertions the index can become corrupted).

The retry path needs to lock the destination, and check the page is
still uninitialized (and then initialize it, WAL-log it, etc).


I'm not entirely convinced the TAP tests are committable, I suspect it
maybe flaky on slower machines (it relies on timeouts etc.). To this may
need some changes. I've attached them mostly to demonstrate the issues.

regards

-- 
Tomas Vondra
From 2d13e1b40a34567214a349ed76fe9b456ff6a557 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 1 Dec 2026 14:43:40 -0500
Subject: [PATCH v1 1/7] Add a TAP test for BRIN desummarization lock order

brinRevmapDesummarizeRange() locks the revmap page before the regular
page, but brin_doupdate() holds the regular pages while it locks the
revmap page to move a summary.  Pause such an update with an injection
point and check that desummarizing a range on the same page does not
deadlock.  The test is expected to fail until the lock order is fixed.

The deadlock was introduced in PostgreSQL 10 by commit c655899ba9a,
which added brin_desummarize_range().
---
 src/backend/access/brin/brin_pageops.c        |   3 +
 src/test/modules/brin/Makefile                |   5 +-
 src/test/modules/brin/meson.build             |   4 +
 .../brin/t/04_desummarize_lock_order.pl       | 154 ++++++++++++++++++
 4 files changed, 165 insertions(+), 1 deletion(-)
 create mode 100644 src/test/modules/brin/t/04_desummarize_lock_order.pl

diff --git a/src/backend/access/brin/brin_pageops.c b/src/backend/access/brin/brin_pageops.c
index 7da97bec43b..48210163d55 100644
--- a/src/backend/access/brin/brin_pageops.c
+++ b/src/backend/access/brin/brin_pageops.c
@@ -19,6 +19,7 @@
 #include "storage/bufmgr.h"
 #include "storage/freespace.h"
 #include "storage/lmgr.h"
+#include "utils/injection_point.h"
 #include "utils/rel.h"
 
 /*
@@ -237,6 +238,8 @@ brin_doupdate(Relation idxrel, BlockNumber pagesPerRange,
 		OffsetNumber newoff;
 		Size		freespace = 0;
 
+		INJECTION_POINT("brin-doupdate-before-revmap-lock", NULL);
+
 		revmapbuf = brinLockRevmapPageForUpdate(revmap, heapBlk);
 
 		START_CRIT_SECTION();
diff --git a/src/test/modules/brin/Makefile b/src/test/modules/brin/Makefile
index e74af891ce7..43033bbda89 100644
--- a/src/test/modules/brin/Makefile
+++ b/src/test/modules/brin/Makefile
@@ -1,10 +1,13 @@
 # src/test/modules/brin/Makefile
 
-EXTRA_INSTALL = contrib/pageinspect contrib/pg_walinspect
+EXTRA_INSTALL = contrib/pageinspect contrib/pg_walinspect \
+	src/test/modules/injection_points
 
 ISOLATION = summarization-and-inprogress-insertion
 TAP_TESTS = 1
 
+export enable_injection_points
+
 ifdef USE_PGXS
 PG_CONFIG = pg_config
 PGXS := $(shell $(PG_CONFIG) --pgxs)
diff --git a/src/test/modules/brin/meson.build b/src/test/modules/brin/meson.build
index 39a8b2fc925..800840f7cf7 100644
--- a/src/test/modules/brin/meson.build
+++ b/src/test/modules/brin/meson.build
@@ -10,9 +10,13 @@ tests += {
     ],
   },
   'tap': {
+    'env': {
+      'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
+    },
     'tests': [
       't/01_workitems.pl',
       't/02_wal_consistency.pl',
+      't/04_desummarize_lock_order.pl',
     ],
   },
 }
diff --git a/src/test/modules/brin/t/04_desummarize_lock_order.pl b/src/test/modules/brin/t/04_desummarize_lock_order.pl
new file mode 100644
index 00000000000..0cd8990c63a
--- /dev/null
+++ b/src/test/modules/brin/t/04_desummarize_lock_order.pl
@@ -0,0 +1,154 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Check that brin_desummarize_range() does not deadlock with a summary update
+# that moves the tuple to another page.
+#
+# brin_doupdate() holds the old and new regular pages while it locks the
+# revmap page to publish the new location.  brinRevmapDesummarizeRange()
+# locks the revmap page first and then the regular page holding the summary.
+# Buffer content locks have no deadlock detection, so if the two meet on the
+# same pages, both wait forever and cannot be canceled.
+
+use strict;
+use warnings FATAL => 'all';
+
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+use Time::HiRes qw(usleep);
+
+plan skip_all => 'Injection points not supported by this build'
+  unless $ENV{enable_injection_points} eq 'yes';
+
+my $node = PostgreSQL::Test::Cluster->new('main');
+$node->init;
+$node->append_conf('postgresql.conf', 'autovacuum = off');
+$node->start;
+
+plan skip_all => 'Extension injection_points not installed'
+  unless $node->check_extension('injection_points');
+
+my $block_size = $node->safe_psql('postgres', 'SHOW block_size');
+
+# One row per heap page, with room to keep an updated row on its page.  All
+# three summaries fit on index block 2.  A summary whose maximum is this long
+# does not fit there, so updating it must move the tuple.
+my $wide_len = $block_size - 72;
+$node->safe_psql(
+	'postgres', q{
+CREATE EXTENSION injection_points;
+CREATE EXTENSION pageinspect;
+CREATE FUNCTION wide_value(len int) RETURNS text
+LANGUAGE sql IMMUTABLE AS $$
+	SELECT left(string_agg(encode(sha256(i::text::bytea), 'base64'), ''
+						   ORDER BY i), len)
+	FROM generate_series(1, len / 44 + 1) i
+$$;
+CREATE TABLE t (a int, b text COLLATE "C", pad text STORAGE PLAIN)
+	WITH (fillfactor = 10);
+INSERT INTO t SELECT i, '', repeat('x', 500) FROM generate_series(0, 2) i;
+CREATE INDEX idx ON t USING brin (b) WITH (pages_per_range = 1);
+});
+
+is( $node->safe_psql(
+		'postgres', q{
+SELECT array_agg(blknum ORDER BY blknum)
+FROM brin_page_items(get_raw_page('idx', 2), 'idx')
+}),
+	'{0,1,2}',
+	'summaries for ranges 0 to 2 are on index block 2');
+
+# Pause the update of range 1 after it has locked the old and new regular
+# pages, but before it locks the revmap page.
+my $updater = $node->background_psql('postgres');
+my $updater_pid = $updater->query_safe('SELECT pg_backend_pid()');
+$updater->query_safe(
+	q{
+SELECT injection_points_set_local();
+SELECT injection_points_attach('brin-doupdate-before-revmap-lock', 'wait');
+});
+$updater->query_until(
+	qr/^updating$/m, qq{
+\\echo updating
+UPDATE t SET b = wide_value($wide_len) WHERE a = 1;
+});
+$node->wait_for_event('client backend', 'brin-doupdate-before-revmap-lock');
+
+# Range 0 is summarized on the same regular page.  Desummarizing it has to
+# wait for that page.
+my $desummarizer = $node->background_psql('postgres');
+my $desummarizer_pid = $desummarizer->query_safe('SELECT pg_backend_pid()');
+$desummarizer->query_until(
+	qr/^desummarizing$/m, q{
+\echo desummarizing
+SELECT brin_desummarize_range('idx', 0);
+});
+$node->poll_query_until(
+	'postgres', qq{
+SELECT wait_event_type = 'Buffer' FROM pg_stat_activity
+WHERE pid = $desummarizer_pid
+})
+  or die 'timed out waiting for desummarization to wait for the regular page';
+
+$node->safe_psql(
+	'postgres', q{
+SELECT injection_points_detach('brin-doupdate-before-revmap-lock');
+SELECT injection_points_wakeup('brin-doupdate-before-revmap-lock');
+});
+
+# Wait until both statements finish.  If both sessions wait for buffer locks
+# for several seconds, they are waiting for each other: neither lock is held
+# by anyone else.
+my $pids = "$updater_pid, $desummarizer_pid";
+my $deadline = time() + $PostgreSQL::Test::Utils::timeout_default;
+my $blocked_since;
+my ($idle, $blocked);
+while (1)
+{
+	($idle, $blocked) = split /\|/, $node->safe_psql(
+		'postgres', qq{
+SELECT count(*) FILTER (WHERE state = 'idle'),
+       count(*) FILTER (WHERE wait_event_type = 'Buffer')
+FROM pg_stat_activity WHERE pid IN ($pids)
+});
+	last if $idle == 2;
+
+	if ($blocked == 2)
+	{
+		$blocked_since //= time();
+		last if time() - $blocked_since >= 5;
+	}
+	else
+	{
+		undef $blocked_since;
+	}
+
+	die 'timed out waiting for the update and desummarization'
+	  if time() > $deadline;
+	usleep(100_000);
+}
+
+is($idle, 2,
+	'desummarization and an off-page summary update on the same page finish');
+
+if ($idle == 2)
+{
+	$updater->quit;
+	$desummarizer->quit;
+	$node->stop;
+}
+else
+{
+	diag $node->safe_psql(
+		'postgres', qq{
+SELECT pid, wait_event_type, wait_event, query FROM pg_stat_activity
+WHERE pid IN ($pids)
+});
+
+	# Neither backend can be canceled while it waits for a buffer lock.
+	$node->stop('immediate');
+	eval { $updater->quit; };
+	eval { $desummarizer->quit; };
+}
+
+done_testing();
-- 
2.56.1

From 85581485e78a323498e36b88c3b6a0d15c5c243f Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 1 Dec 2026 15:36:29 -0500
Subject: [PATCH v1 2/7] Lock the BRIN regular page before the revmap when
 desummarizing

Copy the TID under a shared revmap lock, then recheck it after locking
both pages in update order.  Retry if the summary moved.
---
 src/backend/access/brin/brin_revmap.c | 32 ++++++++++++++++++++-------
 1 file changed, 24 insertions(+), 8 deletions(-)

diff --git a/src/backend/access/brin/brin_revmap.c b/src/backend/access/brin/brin_revmap.c
index 233355cb2d5..9f8bfa87f4d 100644
--- a/src/backend/access/brin/brin_revmap.c
+++ b/src/backend/access/brin/brin_revmap.c
@@ -326,6 +326,7 @@ brinRevmapDesummarizeRange(Relation idxrel, BlockNumber heapBlk)
 	BlockNumber pagesPerRange;
 	RevmapContents *contents;
 	ItemPointerData *iptr;
+	ItemPointerData regTid;
 	ItemPointerData invalidIptr;
 	BlockNumber revmapBlk;
 	Buffer		revmapBuf;
@@ -346,34 +347,43 @@ brinRevmapDesummarizeRange(Relation idxrel, BlockNumber heapBlk)
 		return true;
 	}
 
-	/* Lock the revmap page, obtain the index tuple pointer from it */
-	revmapBuf = brinLockRevmapPageForUpdate(revmap, heapBlk);
+	/*
+	 * Read the tuple's location, but don't hold the revmap lock while
+	 * acquiring the regular page lock.  Updates lock the regular pages before
+	 * the revmap page.
+	 */
+	revmapBuf = revmap_get_buffer(revmap, heapBlk);
+	LockBuffer(revmapBuf, BUFFER_LOCK_SHARE);
 	revmapPg = BufferGetPage(revmapBuf);
 	revmapOffset = HEAPBLK_TO_REVMAP_INDEX(revmap->rm_pagesPerRange, heapBlk);
 
 	contents = (RevmapContents *) PageGetContents(revmapPg);
 	iptr = contents->rm_tids;
 	iptr += revmapOffset;
+	regTid = *iptr;
+	LockBuffer(revmapBuf, BUFFER_LOCK_UNLOCK);
 
-	if (!ItemPointerIsValid(iptr))
+	if (!ItemPointerIsValid(&regTid))
 	{
 		/* no index tuple: range not summarized, we're done */
-		LockBuffer(revmapBuf, BUFFER_LOCK_UNLOCK);
 		brinRevmapTerminate(revmap);
 		return true;
 	}
 
-	regBuf = ReadBuffer(idxrel, ItemPointerGetBlockNumber(iptr));
+	regBuf = ReadBuffer(idxrel, ItemPointerGetBlockNumber(&regTid));
 	LockBuffer(regBuf, BUFFER_LOCK_EXCLUSIVE);
 	regPg = BufferGetPage(regBuf);
 
 	/* if this is no longer a regular page, tell caller to start over */
 	if (!BRIN_IS_REGULAR_PAGE(regPg))
+		goto retry;
+
+	/* A concurrent update could have moved the tuple while we waited. */
+	LockBuffer(revmapBuf, BUFFER_LOCK_EXCLUSIVE);
+	if (!ItemPointerIsValid(iptr) || !ItemPointerEquals(iptr, &regTid))
 	{
 		LockBuffer(revmapBuf, BUFFER_LOCK_UNLOCK);
-		LockBuffer(regBuf, BUFFER_LOCK_UNLOCK);
-		brinRevmapTerminate(revmap);
-		return false;
+		goto retry;
 	}
 
 	regOffset = ItemPointerGetOffsetNumber(iptr);
@@ -431,6 +441,12 @@ brinRevmapDesummarizeRange(Relation idxrel, BlockNumber heapBlk)
 	brinRevmapTerminate(revmap);
 
 	return true;
+
+retry:
+	UnlockReleaseBuffer(regBuf);
+	brinRevmapTerminate(revmap);
+	CHECK_FOR_INTERRUPTS();
+	return false;
 }
 
 /*
-- 
2.56.1

From 5e7d7b145cceeb1799e8948236a0b3127ccbd5b5 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 1 Dec 2026 14:43:40 -0500
Subject: [PATCH v1 3/7] Add a TAP test for an interrupted BRIN page evacuation

Cancel a revmap extension while it evacuates a page, which leaves the
page flagged for evacuation with its live tuples.  An update that fits
on that page then retries forever: brininsert() ignores the flag, but
brin_doupdate() refuses the same-page update.  The test is expected to
fail until such an update moves the tuple instead.

The issue dates back to commit 7516f525941, which added BRIN in
PostgreSQL 9.5.
---
 src/backend/access/brin/brin_pageops.c        |   2 +
 src/test/modules/brin/meson.build             |   1 +
 .../brin/t/05_interrupted_evacuation.pl       | 110 ++++++++++++++++++
 3 files changed, 113 insertions(+)
 create mode 100644 src/test/modules/brin/t/05_interrupted_evacuation.pl

diff --git a/src/backend/access/brin/brin_pageops.c b/src/backend/access/brin/brin_pageops.c
index 48210163d55..485119ee722 100644
--- a/src/backend/access/brin/brin_pageops.c
+++ b/src/backend/access/brin/brin_pageops.c
@@ -593,6 +593,8 @@ brin_evacuate_page(Relation idxRel, BlockNumber pagesPerRange,
 
 			LockBuffer(buf, BUFFER_LOCK_UNLOCK);
 
+			INJECTION_POINT("brin-evacuate-page-before-move", NULL);
+
 			if (!brin_doupdate(idxRel, pagesPerRange, revmap, tup->bt_blkno,
 							   buf, off, tup, sz, tup, sz, false))
 				off--;			/* retry */
diff --git a/src/test/modules/brin/meson.build b/src/test/modules/brin/meson.build
index 800840f7cf7..03ea590e487 100644
--- a/src/test/modules/brin/meson.build
+++ b/src/test/modules/brin/meson.build
@@ -17,6 +17,7 @@ tests += {
       't/01_workitems.pl',
       't/02_wal_consistency.pl',
       't/04_desummarize_lock_order.pl',
+      't/05_interrupted_evacuation.pl',
     ],
   },
 }
diff --git a/src/test/modules/brin/t/05_interrupted_evacuation.pl b/src/test/modules/brin/t/05_interrupted_evacuation.pl
new file mode 100644
index 00000000000..7e177b06bd3
--- /dev/null
+++ b/src/test/modules/brin/t/05_interrupted_evacuation.pl
@@ -0,0 +1,110 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Check that an interrupted page evacuation does not make a later summary
+# update on that page retry forever.
+#
+# Extending the revmap over a regular page sets BRIN_EVACUATE_PAGE on it and
+# then moves the live tuples elsewhere.  If the extension fails partway, the
+# flag stays set and the remaining tuples stay on the page.  brininsert()
+# decides whether an updated summary fits on the old page without checking
+# the flag, but brin_doupdate() refuses to replace a tuple on a flagged page
+# and asks the caller to retry.  The caller then makes the same decision.
+
+use strict;
+use warnings FATAL => 'all';
+
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+plan skip_all => 'Injection points not supported by this build'
+  unless $ENV{enable_injection_points} eq 'yes';
+
+my $node = PostgreSQL::Test::Cluster->new('main');
+$node->init;
+$node->append_conf('postgresql.conf', 'autovacuum = off');
+$node->start;
+
+plan skip_all => 'Extension injection_points not installed'
+  unless $node->check_extension('injection_points');
+
+# One row per heap page, with room to keep an updated row on its page.  The
+# summaries of ranges 0 to 2 are on index block 2, the first block the revmap
+# will need when it grows.
+$node->safe_psql(
+	'postgres', q{
+CREATE EXTENSION injection_points;
+CREATE EXTENSION pageinspect;
+CREATE TABLE t (a int, pad text STORAGE PLAIN) WITH (fillfactor = 10);
+INSERT INTO t SELECT i, repeat('x', 500) FROM generate_series(0, 2) i;
+CREATE INDEX idx ON t USING brin (a) WITH (pages_per_range = 1);
+});
+
+# Make the heap long enough that summarizing its last range needs a second
+# revmap page.
+my $ranges = $node->safe_psql('postgres',
+	q{SELECT count(*) FROM brin_revmap_data(get_raw_page('idx', 1))});
+$node->safe_psql('postgres',
+	"INSERT INTO t SELECT i, repeat('x', 500) FROM generate_series(3, $ranges) i"
+);
+is( $node->safe_psql(
+		'postgres',
+		q{SELECT pg_relation_size('t') / current_setting('block_size')::int}),
+	$ranges + 1,
+	'one heap page per row');
+
+# Cancel the revmap extension before it moves the first live tuple.
+my $extender = $node->background_psql('postgres', on_error_stop => 0);
+my $extender_pid = $extender->query_safe('SELECT pg_backend_pid()');
+$extender->query_safe(
+	q{
+SELECT injection_points_set_local();
+SELECT injection_points_attach('brin-evacuate-page-before-move', 'wait');
+});
+$extender->query_until(
+	qr/^extending$/m, qq{
+\\echo extending
+SELECT brin_summarize_range('idx', $ranges);
+});
+$node->wait_for_event('client backend', 'brin-evacuate-page-before-move');
+$node->safe_psql('postgres', "SELECT pg_cancel_backend($extender_pid)");
+$extender->query('SELECT 1');
+like(
+	$extender->{stderr},
+	qr/canceling statement due to user request/,
+	'revmap extension was canceled during evacuation');
+$extender->quit;
+
+# BrinSpecialSpace ends with the flags and the page type, two bytes each.
+# BRIN_EVACUATE_PAGE is the only flag, so either flag byte holds it.
+is( $node->safe_psql(
+		'postgres', q{
+SELECT brin_page_type(p), get_byte(p, bs - 4) | get_byte(p, bs - 3)
+FROM (SELECT get_raw_page('idx', 2) AS p,
+             current_setting('block_size')::int AS bs) s
+}),
+	'regular|1',
+	'block 2 is still a regular page, marked for evacuation');
+is( $node->safe_psql(
+		'postgres', q{
+SELECT array_agg(blknum ORDER BY blknum)
+FROM brin_page_items(get_raw_page('idx', 2), 'idx')
+}),
+	'{0,1,2}',
+	'the live summaries are still on block 2');
+
+# Widening the range 1 summary from {1 .. 1} to {-1 .. 1} does not change
+# its size.  The retry loop never ends, so the timeout only has to cover one
+# single-row update.
+my ($ret, $stdout, $stderr) = $node->psql(
+	'postgres', q{
+SET statement_timeout = '10s';
+UPDATE t SET a = -1 WHERE a = 1 RETURNING ctid;
+});
+is($ret, 0, 'updating a summary on the flagged page finishes')
+  or diag $stderr;
+like($stdout, qr/^\(1,\d+\)$/, 'updated row stayed in range 1');
+
+$node->stop;
+
+done_testing();
-- 
2.56.1

From e03e3101ed2e5c8b654ac55009a05f4d7e012726 Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 1 Dec 2026 15:36:29 -0500
Subject: [PATCH v1 4/7] Move BRIN updates off pages marked for evacuation

Check the evacuation flag when choosing whether to update in
place. Otherwise an interrupted evacuation can leave later updates
retrying forever even when the new tuple fits.
---
 src/backend/access/brin/brin.c         |  2 ++
 src/backend/access/brin/brin_pageops.c | 22 ++++++++++++++--------
 2 files changed, 16 insertions(+), 8 deletions(-)

diff --git a/src/backend/access/brin/brin.c b/src/backend/access/brin/brin.c
index 5fc40845c17..d8b7645d54e 100644
--- a/src/backend/access/brin/brin.c
+++ b/src/backend/access/brin/brin.c
@@ -1846,7 +1846,9 @@ summarize_range(IndexInfo *indexInfo, BrinBuildState *state, Relation heapRel,
 		 */
 		newtup = brin_form_tuple(state->bs_bdesc,
 								 heapBlk, state->bs_dtuple, &newsize);
+		LockBuffer(phbuf, BUFFER_LOCK_SHARE);
 		samepage = brin_can_do_samepage_update(phbuf, phsz, newsize);
+		LockBuffer(phbuf, BUFFER_LOCK_UNLOCK);
 		didupdate =
 			brin_doupdate(state->bs_irel, state->bs_pagesPerRange,
 						  state->bs_rmAccess, heapBlk, phbuf, offset,
diff --git a/src/backend/access/brin/brin_pageops.c b/src/backend/access/brin/brin_pageops.c
index 485119ee722..0a5bcfd73b7 100644
--- a/src/backend/access/brin/brin_pageops.c
+++ b/src/backend/access/brin/brin_pageops.c
@@ -173,8 +173,7 @@ brin_doupdate(Relation idxrel, BlockNumber pagesPerRange,
 	 * caller told us there isn't, if a concurrent update moved another tuple
 	 * elsewhere or replaced a tuple with a smaller one.
 	 */
-	if (((BrinPageFlags(oldpage) & BRIN_EVACUATE_PAGE) == 0) &&
-		brin_can_do_samepage_update(oldbuf, origsz, newsz))
+	if (brin_can_do_samepage_update(oldbuf, origsz, newsz))
 	{
 		START_CRIT_SECTION();
 		if (!PageIndexTupleOverwrite(oldpage, oldoff, newtup, newsz))
@@ -220,8 +219,8 @@ brin_doupdate(Relation idxrel, BlockNumber pagesPerRange,
 	else if (newbuf == InvalidBuffer)
 	{
 		/*
-		 * Not enough space, but caller said that there was. Tell them to
-		 * start over.
+		 * The caller expected to update in place, but the page no longer has
+		 * room or is being evacuated.  Have the caller start over.
 		 */
 		LockBuffer(oldbuf, BUFFER_LOCK_UNLOCK);
 		return false;
@@ -319,14 +318,21 @@ brin_doupdate(Relation idxrel, BlockNumber pagesPerRange,
 }
 
 /*
- * Return whether brin_doupdate can do a samepage update.
+ * Return whether brin_doupdate can do a samepage update.  The caller must
+ * hold a lock on the buffer.
  */
 bool
 brin_can_do_samepage_update(Buffer buffer, Size origsz, Size newsz)
 {
-	return
-		((newsz <= origsz) ||
-		 PageGetExactFreeSpace(BufferGetPage(buffer)) >= (newsz - origsz));
+	Page		page = BufferGetPage(buffer);
+
+	Assert(BufferIsLockedByMe(buffer));
+
+	/* Even a tuple that fits must move off a page marked for evacuation. */
+	if (BrinPageFlags(page) & BRIN_EVACUATE_PAGE)
+		return false;
+
+	return newsz <= origsz || PageGetExactFreeSpace(page) >= (newsz - origsz);
 }
 
 /*
-- 
2.56.1

From ac4312b9f0b9c5c0f425f712e706bfa49ae90fae Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 1 Dec 2026 14:43:40 -0500
Subject: [PATCH v1 5/7] Add a TAP test for BRIN index extension after page
 evacuation

Pause a summary update before it locks its old page again, and extend
the revmap over that page meanwhile.  brin_getinsertbuffer() then
initializes the page it just added without locking it, which fails an
assertion in MarkBufferDirty().  The test is expected to fail in
assertion-enabled builds until the new page is locked first.

The missing lock was introduced by commit ccc4c074994 (backpatched to
9.5 as fc0a6402306), which made brin_getinsertbuffer() initialize such
a page instead of leaving it uninitialized.
---
 src/backend/access/brin/brin_pageops.c        |   2 +
 src/test/modules/brin/meson.build             |   1 +
 .../brin/t/06_extend_after_evacuation.pl      | 140 ++++++++++++++++++
 3 files changed, 143 insertions(+)
 create mode 100644 src/test/modules/brin/t/06_extend_after_evacuation.pl

diff --git a/src/backend/access/brin/brin_pageops.c b/src/backend/access/brin/brin_pageops.c
index 0a5bcfd73b7..74014b742f6 100644
--- a/src/backend/access/brin/brin_pageops.c
+++ b/src/backend/access/brin/brin_pageops.c
@@ -83,6 +83,8 @@ brin_doupdate(Relation idxrel, BlockNumber pagesPerRange,
 
 	if (!samepage)
 	{
+		INJECTION_POINT("brin-doupdate-before-getinsertbuffer", NULL);
+
 		/* need a page on which to put the item */
 		newbuf = brin_getinsertbuffer(idxrel, oldbuf, newsz, &extended);
 		if (!BufferIsValid(newbuf))
diff --git a/src/test/modules/brin/meson.build b/src/test/modules/brin/meson.build
index 03ea590e487..ae42a5f2c34 100644
--- a/src/test/modules/brin/meson.build
+++ b/src/test/modules/brin/meson.build
@@ -18,6 +18,7 @@ tests += {
       't/02_wal_consistency.pl',
       't/04_desummarize_lock_order.pl',
       't/05_interrupted_evacuation.pl',
+      't/06_extend_after_evacuation.pl',
     ],
   },
 }
diff --git a/src/test/modules/brin/t/06_extend_after_evacuation.pl b/src/test/modules/brin/t/06_extend_after_evacuation.pl
new file mode 100644
index 00000000000..9cc3b8d33a5
--- /dev/null
+++ b/src/test/modules/brin/t/06_extend_after_evacuation.pl
@@ -0,0 +1,140 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Check that brin_getinsertbuffer() locks a newly extended page before it
+# initializes it after finding that the old page became a revmap page.
+#
+# brin_doupdate() does not hold a lock on the old tuple's page until
+# brin_getinsertbuffer() locks it.  In between, a revmap extension can move the
+# tuple away and reinitialize the page as a revmap page.  If
+# brin_getinsertbuffer() has already extended the index for the new tuple, it
+# then initializes that page without the exclusive content lock that
+# MarkBufferDirty() requires.  Only assertion-enabled builds detect this.
+
+use strict;
+use warnings FATAL => 'all';
+
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+plan skip_all => 'Injection points not supported by this build'
+  unless $ENV{enable_injection_points} eq 'yes';
+
+my $node = PostgreSQL::Test::Cluster->new('main');
+$node->init;
+$node->append_conf(
+	'postgresql.conf', q{
+autovacuum = off
+restart_after_crash = on
+});
+$node->start;
+
+plan skip_all => 'Extension injection_points not installed'
+  unless $node->check_extension('injection_points');
+
+# The free space map records a BRIN page in category 254 at most, because the
+# page has less than MaxFSMRequestSize free.  A larger request needs category
+# 255, so it always extends the index.  With smaller pages, the largest BRIN
+# tuple does not reach that category.
+my $block_size = $node->safe_psql('postgres', 'SHOW block_size');
+if ($block_size < 8192)
+{
+	$node->stop;
+	plan skip_all => 'test requires BLCKSZ of at least 8192';
+}
+note 'assertions are disabled, so the missing lock is not detected'
+  if $node->safe_psql('postgres', 'SHOW debug_assertions') ne 'on';
+
+# One row per heap page, with room to keep an updated row on its page.  The
+# summaries of ranges 0 to 2 are on index block 2, the first block the revmap
+# will need when it grows.
+my $wide_len = $block_size - 72;
+$node->safe_psql(
+	'postgres', q{
+CREATE EXTENSION injection_points;
+CREATE EXTENSION pageinspect;
+CREATE FUNCTION wide_value(len int) RETURNS text
+LANGUAGE sql IMMUTABLE AS $$
+	SELECT left(string_agg(encode(sha256(i::text::bytea), 'base64'), ''
+						   ORDER BY i), len)
+	FROM generate_series(1, len / 44 + 1) i
+$$;
+CREATE TABLE t (a int, b text COLLATE "C", pad text STORAGE PLAIN)
+	WITH (fillfactor = 10);
+INSERT INTO t SELECT i, '', repeat('x', 500) FROM generate_series(0, 2) i;
+CREATE INDEX idx ON t USING brin (b) WITH (pages_per_range = 1);
+});
+
+# A summary from '' to the wide value cannot be compressed, and no existing
+# page can be recorded with enough free space for it.
+is( $node->safe_psql(
+		'postgres', qq{
+CREATE TABLE probe (b text COLLATE "C");
+INSERT INTO probe VALUES (''), (wide_value($wide_len));
+CREATE INDEX probe_idx ON probe USING brin (b) WITH (pages_per_range = 1);
+SELECT special - upper > $block_size / 256 * 254
+FROM page_header(get_raw_page('probe_idx', 2));
+}),
+	't',
+	'widened summary is larger than any recorded free space');
+
+# Make the heap long enough that summarizing its last range needs a second
+# revmap page.
+my $ranges = $node->safe_psql('postgres',
+	q{SELECT count(*) FROM brin_revmap_data(get_raw_page('idx', 1))});
+$node->safe_psql('postgres',
+	"INSERT INTO t SELECT i, '', repeat('x', 500) FROM generate_series(3, $ranges) i"
+);
+
+# Pause the update of range 1 after it decided the summary must move, but
+# before it locks the old page again.
+my $updater = $node->background_psql('postgres', on_error_stop => 0);
+$updater->query_safe(
+	q{
+SELECT injection_points_set_local();
+SELECT injection_points_attach('brin-doupdate-before-getinsertbuffer', 'wait');
+});
+$updater->query_until(
+	qr/^updating$/m, qq{
+\\echo updating
+UPDATE t SET b = wide_value($wide_len) WHERE a = 1;
+\\echo updated
+});
+$node->wait_for_event('client backend',
+	'brin-doupdate-before-getinsertbuffer');
+
+# Meanwhile, extend the revmap over block 2.  This moves the range 1 summary.
+is( $node->safe_psql(
+		'postgres', "SELECT brin_summarize_range('idx', $ranges)"),
+	'1',
+	'summarized the range that needs a second revmap page');
+is( $node->safe_psql(
+		'postgres', q{SELECT brin_page_type(get_raw_page('idx', 2))}),
+	'revmap',
+	'the old page of the paused update became a revmap page');
+
+# A crash can also terminate the waking session, so ignore its result.
+my $log_offset = -s $node->logfile;
+$node->psql(
+	'postgres', q{
+SELECT injection_points_detach('brin-doupdate-before-getinsertbuffer');
+SELECT injection_points_wakeup('brin-doupdate-before-getinsertbuffer');
+});
+
+# If the update's psql loses its connection instead of finishing, wait for the
+# server to reinitialize after the crash.
+if ($updater->query_until(qr/^updated$/m, '') !~ /^updated$/m)
+{
+	$node->wait_for_log(qr/database system is ready to accept connections/,
+		$log_offset);
+}
+
+ok(!$node->log_contains(qr/TRAP:|terminated by signal/, $log_offset),
+	'no backend failed an assertion or crashed');
+is($node->safe_psql('postgres', 'SELECT length(b) FROM t WHERE a = 1'),
+	$wide_len, 'the update was committed');
+
+eval { $updater->quit; };
+$node->stop;
+
+done_testing();
-- 
2.56.1

From 75bc08254e0dc3657538f2b2047689ea6242d8ba Mon Sep 17 00:00:00 2001
From: Tomas Vondra <[email protected]>
Date: Tue, 1 Dec 2026 15:37:40 -0500
Subject: [PATCH v1 6/7] Lock new BRIN pages before initializing them on retry

If evacuation invalidates the source page, lock the newly extended page
before initializing it.  Leave it intact if the revmap already used it.
---
 src/backend/access/brin/brin_pageops.c | 22 ++++++++++++----------
 1 file changed, 12 insertions(+), 10 deletions(-)

diff --git a/src/backend/access/brin/brin_pageops.c b/src/backend/access/brin/brin_pageops.c
index 74014b742f6..d27b8c0cc1d 100644
--- a/src/backend/access/brin/brin_pageops.c
+++ b/src/backend/access/brin/brin_pageops.c
@@ -791,20 +791,22 @@ brin_getinsertbuffer(Relation irel, Buffer oldbuf, Size itemsz,
 				 * uninitialized page get in the FSM, so we need to initialize
 				 * it first.
 				 */
-				if (*extended)
-					brin_initialize_empty_new_buffer(irel, buf);
-
-				if (extensionLockHeld)
-					UnlockRelationForExtension(irel, ExclusiveLock);
-
-				ReleaseBuffer(buf);
-
 				if (*extended)
 				{
+					LockBuffer(buf, BUFFER_LOCK_EXCLUSIVE);
+					if (extensionLockHeld)
+						UnlockRelationForExtension(irel, ExclusiveLock);
+
+					/* A revmap extension might already have claimed it. */
+					if (PageIsNew(BufferGetPage(buf)))
+						brin_initialize_empty_new_buffer(irel, buf);
+					UnlockReleaseBuffer(buf);
 					FreeSpaceMapVacuumRange(irel, newblk, newblk + 1);
 					/* shouldn't matter, but don't confuse caller */
 					*extended = false;
 				}
+				else
+					ReleaseBuffer(buf);
 
 				return InvalidBuffer;
 			}
@@ -888,8 +890,8 @@ brin_getinsertbuffer(Relation irel, Buffer oldbuf, Size itemsz,
  * Also, because we would not WAL-log the action that would initialize the
  * page, the page would go uninitialized in a standby (or after recovery).
  *
- * While we record the page in FSM here, caller is responsible for doing FSM
- * upper-page update if that seems appropriate.
+ * The caller must hold an exclusive lock on the buffer and is responsible for
+ * updating the upper FSM pages if appropriate.
  */
 static void
 brin_initialize_empty_new_buffer(Relation idxrel, Buffer buffer)
-- 
2.56.1

Reply via email to