Hi,

I ran into an undetected deadlock between a committing backend and the
walsender decoding its transaction, when the transaction writes a row
containing a composite type whose relation it holds AccessExclusiveLock
on, and synchronous replication is waiting for that walsender.

Repro (two clusters, publisher and subscriber, no extensions):

  -- publisher: wal_level = logical
  CREATE PUBLICATION p FOR ALL TABLES;

  -- subscriber
  CREATE TYPE ct AS (a int, b text);
  CREATE TABLE t (id int PRIMARY KEY, v ct);
  CREATE SUBSCRIPTION sub1
      CONNECTION 'port=5491 dbname=postgres application_name=sub1'
      PUBLICATION p WITH (streaming = off);

  -- publisher
  ALTER SYSTEM SET synchronous_standby_names = 'sub1';
  SELECT pg_reload_conf();

  BEGIN;
  CREATE TYPE ct AS (a int, b text);
  CREATE TABLE t (id int PRIMARY KEY, v ct);
  INSERT INTO t VALUES (1, ROW(1, 'x'));
  COMMIT;                                   -- never returns

On the publisher:

  backend_type   | wait_event | relation | mode                | granted
  ---------------+------------+----------+---------------------+--------
  client backend | SyncRep    | ct       | AccessExclusiveLock | t
  walsender      | relation   | ct       | AccessShareLock     | f

  LOG:  process NNN still waiting for AccessShareLock on relation NNNNN
        of database NNNNN after 1000.000 ms

The subscriber receives nothing, so it never confirms, and nothing
times out: the subscriber's wal_receiver_timeout eventually drops the
connection, but the stuck walsender keeps the slot active, so every
reconnect fails with 'replication slot "sub1" is active for PID NNN'.

The same thing happens without the type being created in the same
transaction, e.g. an existing table used as a row type that the
committing transaction ALTERs:

  BEGIN;
  ALTER TABLE rt ALTER COLUMN b SET DEFAULT 'y';
  INSERT INTO t2 VALUES (1, ROW(1, 'x')::rt);  -- t2.v is of type rt
  COMMIT;

and, as a stall rather than a deadlock, when a different, still-open
transaction holds AccessExclusiveLock on the type's relation: the
walsender then blocks every synchronous commit behind it until that
transaction ends.

Streaming of in-progress transactions is not involved (the repro uses
streaming = off, and pg_stat_replication_slots shows stream_txns = 0).

Analysis:

CommitTransaction() flushes the commit record and waits in
SyncRepWaitForLSN() before releasing its locks.  The walsender decodes
the transaction from that commit record, and pgoutput formats the
composite column with record_out() -> lookup_rowtype_tupdesc() ->
load_typcache_tupdesc(), which does

    rel = relation_open(typentry->typrelid, AccessShareLock);

That waits behind the committing transaction's AccessExclusiveLock,
while the committing transaction waits for the walsender: the backend
sleeping in SyncRepWaitForLSN() can only be released by a walsender
calling SyncRepReleaseWaiters() when the standby acknowledges the commit
LSN, and the blocked walsender neither sends the transaction nor reads
the standby's replies.  The deadlock detector only sees the walsender's
lock wait; the other edge is a latch wait in SyncRepWaitForLSN(), so no
cycle is found.

This is similar to the documented caveat in "Synchronous Replication
Support for Logical Decoding" about exclusively locking [user] catalog
tables, but here the table is an ordinary user table, and the lock can
be taken implicitly by CREATE TYPE / CREATE TABLE / ALTER TABLE.

load_typcache_tupdesc() has taken this lock since 2004 (375369acd1c),
so as far as I can tell all supported branches are affected.  I
reproduced it on master and REL_19_STABLE.

Proposed fix:

While decoding (HistoricSnapshotActive()), open the type's relation
without a lock, using RelationIdGetRelation()/RelationClose().  Decoding
reads the catalogs through the historic snapshot, which concurrent DDL
cannot change, and ReorderBufferProcessTXN() already opens the decoded
relations the same way, without locking them.  All other callers still
take AccessShareLock.  With the attached patch the repro above commits
immediately.

The attached patch also adds a TAP test in src/test/subscription.

For background: we first hit this in an extension that waits for its
peers to acknowledge DDL in the middle of a transaction, which closes
the same cycle without synchronous replication.

Thoughts?  In particular, I'd be glad to hear whether skipping the lock
under a historic snapshot is acceptable here, or whether it would be
better handled elsewhere.

Regards,
Dipak Dudhabhate
EDB
From 5f03276dfb2c7c5a9e77716699086c73e9707a05 Mon Sep 17 00:00:00 2001
From: Dipak Dudhabhate <[email protected]>
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

Reply via email to