From ac4312b9f0b9c5c0f425f712e706bfa49ae90fae Mon Sep 17 00:00:00 2001
From: Tomas Vondra <tomas@vondra.me>
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

