From 2d13e1b40a34567214a349ed76fe9b456ff6a557 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 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

