From 5f03276dfb2c7c5a9e77716699086c73e9707a05 Mon Sep 17 00:00:00 2001
From: Dipak Dudhabhate <dipak.dudhabhate@enterprisedb.com>
Date: Tue, 1 Dec 2026 15:56:17 +0530
Subject: [PATCH v1] Don't lock a composite type's relation in typcache during
 decoding

load_typcache_tupdesc() opened the type's relation with AccessShareLock.
When a walsender formats a row containing that type, this can block on
a transaction holding AccessExclusiveLock on the relation: the one being
decoded, if it created or altered the type, or another one.  If that
transaction waits for the walsender, as a commit does under synchronous
replication while still holding its locks, the two deadlock, and the
deadlock detector cannot see it since the commit waits on a latch.

While decoding (HistoricSnapshotActive()), open the relation without a
lock, as ReorderBufferProcessTXN() does for decoded relations.  Decoding
reads the catalogs through its historic snapshot, which concurrent DDL
cannot change.  Add a TAP test.
---
 src/backend/utils/cache/typcache.c            | 27 +++++-
 src/test/subscription/meson.build             |  1 +
 .../t/039_decoding_composite_lock.pl          | 96 +++++++++++++++++++
 3 files changed, 122 insertions(+), 2 deletions(-)
 create mode 100644 src/test/subscription/t/039_decoding_composite_lock.pl

diff --git a/src/backend/utils/cache/typcache.c b/src/backend/utils/cache/typcache.c
index f969b435cb7..01cbac46c31 100644
--- a/src/backend/utils/cache/typcache.c
+++ b/src/backend/utils/cache/typcache.c
@@ -71,6 +71,7 @@
 #include "utils/lsyscache.h"
 #include "utils/memutils.h"
 #include "utils/rel.h"
+#include "utils/snapmgr.h"
 #include "utils/syscache.h"
 #include "utils/typcache.h"
 
@@ -954,7 +955,26 @@ load_typcache_tupdesc(TypeCacheEntry *typentry)
 	if (!OidIsValid(typentry->typrelid))	/* should not happen */
 		elog(ERROR, "invalid typrelid for composite type %u",
 			 typentry->type_id);
-	rel = relation_open(typentry->typrelid, AccessShareLock);
+
+	/*
+	 * During logical decoding, open the relation without taking a lock.  The
+	 * catalogs are read through a historic snapshot, which concurrent DDL
+	 * cannot change, and ReorderBufferProcessTXN() opens the decoded
+	 * relations the same way.  Taking AccessShareLock here would wait for any
+	 * transaction holding AccessExclusiveLock on the type's relation,
+	 * including the one being decoded.  If that transaction is itself waiting
+	 * for its changes to be replicated, as with synchronous replication, the
+	 * two wait for each other and the deadlock detector cannot see it.
+	 */
+	if (HistoricSnapshotActive())
+	{
+		rel = RelationIdGetRelation(typentry->typrelid);
+		if (!RelationIsValid(rel))
+			elog(ERROR, "could not open relation with OID %u",
+				 typentry->typrelid);
+	}
+	else
+		rel = relation_open(typentry->typrelid, AccessShareLock);
 	Assert(rel->rd_rel->reltype == typentry->type_id);
 
 	/*
@@ -974,7 +994,10 @@ load_typcache_tupdesc(TypeCacheEntry *typentry)
 	 */
 	typentry->tupDesc_identifier = ++tupledesc_id_counter;
 
-	relation_close(rel, AccessShareLock);
+	if (HistoricSnapshotActive())
+		RelationClose(rel);
+	else
+		relation_close(rel, AccessShareLock);
 }
 
 /*
diff --git a/src/test/subscription/meson.build b/src/test/subscription/meson.build
index e71e95c6297..1c37cc17278 100644
--- a/src/test/subscription/meson.build
+++ b/src/test/subscription/meson.build
@@ -48,6 +48,7 @@ tests += {
       't/036_sequences.pl',
       't/037_except.pl',
       't/038_walsnd_shutdown_timeout.pl',
+      't/039_decoding_composite_lock.pl',
       't/100_bugs.pl',
     ],
   },
diff --git a/src/test/subscription/t/039_decoding_composite_lock.pl b/src/test/subscription/t/039_decoding_composite_lock.pl
new file mode 100644
index 00000000000..656f7121129
--- /dev/null
+++ b/src/test/subscription/t/039_decoding_composite_lock.pl
@@ -0,0 +1,96 @@
+
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test that decoding a row containing a composite type does not lock the
+# type's relation.  With synchronous replication, the committing transaction
+# still holds its locks while it waits for the walsender, so if the walsender
+# waited for a lock on the type's relation that the transaction holds
+# AccessExclusiveLock on, the two would deadlock without the deadlock
+# detector noticing.
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $node_publisher = PostgreSQL::Test::Cluster->new('publisher');
+$node_publisher->init(allows_streaming => 'logical');
+$node_publisher->start;
+
+my $node_subscriber = PostgreSQL::Test::Cluster->new('subscriber');
+$node_subscriber->init;
+$node_subscriber->start;
+
+my $publisher_connstr = $node_publisher->connstr . ' dbname=postgres';
+
+# tab_rt is used as the row type of tab_comp.v.
+my $ddl = qq(
+	CREATE TABLE tab_rt (a int, b text);
+	CREATE TABLE tab_comp (id int PRIMARY KEY, v tab_rt););
+$node_publisher->safe_psql('postgres', $ddl);
+$node_subscriber->safe_psql('postgres', $ddl);
+
+# The publisher creates these inside the tested transaction; the subscriber
+# needs them beforehand, or applying the transaction would fail and the
+# synchronous commit would wait for it forever.
+$node_subscriber->safe_psql(
+	'postgres', qq(
+	CREATE TYPE comp_new AS (a int, b text);
+	CREATE TABLE tab_new (id int PRIMARY KEY, v comp_new);));
+
+$node_publisher->safe_psql('postgres',
+	"CREATE PUBLICATION tap_pub FOR ALL TABLES");
+$node_subscriber->safe_psql('postgres',
+	"CREATE SUBSCRIPTION tap_sub CONNECTION '$publisher_connstr application_name=tap_sub' PUBLICATION tap_pub WITH (streaming = off)"
+);
+$node_subscriber->wait_for_subscription_sync($node_publisher, 'tap_sub');
+
+# Make commits on the publisher wait for the subscriber.
+$node_publisher->append_conf('postgresql.conf',
+	"synchronous_standby_names = 'tap_sub'");
+$node_publisher->reload;
+$node_publisher->poll_query_until('postgres',
+	"SELECT sync_state = 'sync' FROM pg_stat_replication WHERE application_name = 'tap_sub'"
+) or die "timed out waiting for tap_sub to become a synchronous standby";
+
+my ($ret, $stdout, $stderr, $timed_out);
+
+# The transaction takes AccessExclusiveLock on the row type's relation, then
+# writes a row of that type.
+$ret = $node_publisher->psql(
+	'postgres', qq(
+	BEGIN;
+	ALTER TABLE tab_rt ALTER COLUMN b SET DEFAULT 'y';
+	INSERT INTO tab_comp VALUES (1, ROW(1, 'x'));
+	COMMIT;),
+	stdout => \$stdout,
+	stderr => \$stderr,
+	timeout => $PostgreSQL::Test::Utils::timeout_default,
+	timed_out => \$timed_out);
+ok(!$timed_out && $ret == 0,
+	'commit writing a row type whose relation it locked does not deadlock');
+
+$node_publisher->wait_for_catchup('tap_sub');
+is( $node_subscriber->safe_psql('postgres', "SELECT * FROM tab_comp"),
+	'1|(1,x)',
+	'row of the locked row type replicated');
+
+# The same with a composite type created in the transaction.
+$ret = $node_publisher->psql(
+	'postgres', qq(
+	BEGIN;
+	CREATE TYPE comp_new AS (a int, b text);
+	CREATE TABLE tab_new (id int PRIMARY KEY, v comp_new);
+	INSERT INTO tab_new VALUES (1, ROW(1, 'x'));
+	COMMIT;),
+	stdout => \$stdout,
+	stderr => \$stderr,
+	timeout => $PostgreSQL::Test::Utils::timeout_default,
+	timed_out => \$timed_out);
+ok(!$timed_out && $ret == 0,
+	'commit writing a composite type it created does not deadlock');
+
+$node_subscriber->stop('fast');
+$node_publisher->stop('fast');
+
+done_testing();
-- 
2.53.0

