From edccf2ffe2763b140d8d9b258e3ad08dd0a6b69b Mon Sep 17 00:00:00 2001 From: Zhijie Hou Date: Fri, 4 Dec 2026 20:17:59 +0800 Subject: [PATCH v1 4/5] Lock the subscription during ownership changes. AlterSubscriptionOwner() and AlterSubscriptionOwner_oid() did not acquire a lock on the subscription object before locking the conflict log table and updating the pg_subscription tuple. Consequently, a transaction that ran ALTER SUBSCRIPTION (updating the pg_subscription tuple) before dropping or accessing the conflict log table could still deadlock with a concurrent ALTER SUBSCRIPTION ... OWNER TO or REASSIGN OWNED BY command. Fix this by acquiring AccessExclusiveLock on the subscription in AlterSubscriptionOwner() (via get_object_address() after an initial ownership check) and AlterSubscriptionOwner_oid() before fetching the pg_subscription tuple passed to AlterSubscriptionOwner_internal(). Because holding AccessExclusiveLock on the subscription blocks workers that acquire AccessShareLock on the subscription (including any new apply worker needed to resolve prepared transactions), follow DropSubscription() when changing the conflict log table's owner by stopping all subscription workers and disallowing the owner change while prepared transactions of the subscription exist; this also avoids deadlocking with a worker that holds a lock on the conflict log table or waiting indefinitely on a prepared transaction's lock. Discussion: https://postgr.es/m/CALdSSPhJJsrpVFroxSNLYCN=Pxj6Son6RzSLzxwYzmQwxWh4Rw@mail.gmail.com --- doc/src/sgml/ref/alter_subscription.sgml | 9 +- src/backend/commands/subscriptioncmds.c | 108 +++++++++++++++-------- src/test/subscription/t/035_conflicts.pl | 33 +++++-- 3 files changed, 107 insertions(+), 43 deletions(-) diff --git a/doc/src/sgml/ref/alter_subscription.sgml b/doc/src/sgml/ref/alter_subscription.sgml index 8751a18aba9..2b746315429 100644 --- a/doc/src/sgml/ref/alter_subscription.sgml +++ b/doc/src/sgml/ref/alter_subscription.sgml @@ -426,7 +426,14 @@ ALTER SUBSCRIPTION name RENAME TO < new_owner - The user name of the new owner of the subscription. + The user name of the new owner of the subscription. If + conflict_log_destination + is set to table or all, ownership + of the associated conflict log table is changed as well. However, in + that case, changing the owner is not allowed while the subscription has + prepared transactions (see + two_phase), + because such a transaction may hold a lock on the conflict log table. diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c index 67eccf45974..88933f36c02 100644 --- a/src/backend/commands/subscriptioncmds.c +++ b/src/backend/commands/subscriptioncmds.c @@ -3143,14 +3143,15 @@ ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missi } /* - * Internal workhorse for changing a subscription owner + * Internal workhorse for changing a subscription owner. + * + * Caller must have already acquired AccessExclusiveLock on the subscription. */ static void AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId) { Form_pg_subscription form; AclResult aclresult; - HeapTuple curtup = tup; form = (Form_pg_subscription) GETSTRUCT(tup); @@ -3203,32 +3204,46 @@ AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId) /* * Update owner of the conflict log table first, if it exists, before - * updating the subscription's row. Changing its owner can wait for a - * prepared transaction of this subscription that holds a lock on it. If - * we had already updated the row, the apply worker could wait for us when - * it updates the row itself, e.g. to disable the subscription after an - * error, while we wait for the prepared transaction to be resolved by the - * apply worker. + * updating the subscription's row, keeping the lock acquisition order + * consistent with ALTER SUBSCRIPTION and DROP SUBSCRIPTION. */ if (OidIsValid(form->subconflictlogrelid)) { - Oid subid = form->oid; + List *subworkers; - ATExecChangeOwner(form->subconflictlogrelid, newOwnerId, true, - AccessExclusiveLock); + /* + * Stop all the subscription workers so that no worker prepares a new + * transaction or waits on the subscription lock (for example, in + * clear_subscription_skip_lsn()) while holding a lock on the conflict + * log table. Any newly launched worker will wait on the subscription + * lock in InitializeLogRepWorker() until the end of the transaction. + */ + subworkers = logicalrep_workers_find(form->oid, false, true); + foreach_ptr(LogicalRepWorker, w, subworkers) + logicalrep_worker_stop(w->type, w->subid, w->relid); + list_free(subworkers); /* - * The row may have been updated while we waited for the lock, so - * update its current version. + * Disallow changing the owner when prepared transactions exist, as a + * prepared transaction may hold a lock on the conflict log table that + * cannot be released while we hold the subscription lock. See + * DropSubscription() for details. */ - curtup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid)); - if (!HeapTupleIsValid(curtup)) - elog(ERROR, "cache lookup failed for subscription %u", subid); - form = (Form_pg_subscription) GETSTRUCT(curtup); + if (form->subtwophasestate != LOGICALREP_TWOPHASE_STATE_DISABLED && + LookupGXactBySubid(form->oid)) + ereport(ERROR, + errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), + errmsg("cannot change owner of subscription \"%s\" when prepared transactions exist", + NameStr(form->subname)), + errdetail("A prepared transaction of the subscription may hold a lock on the subscription's conflict log table."), + errhint("Resolve these transactions and try again.")); + + ATExecChangeOwner(form->subconflictlogrelid, newOwnerId, true, + AccessExclusiveLock); } form->subowner = newOwnerId; - CatalogTupleUpdate(rel, &curtup->t_self, curtup); + CatalogTupleUpdate(rel, &tup->t_self, tup); /* Update owner dependency reference */ changeDependencyOnOwner(SubscriptionRelationId, @@ -3241,9 +3256,6 @@ AlterSubscriptionOwner_internal(Relation rel, HeapTuple tup, Oid newOwnerId) /* Wake up related background processes to handle this change quickly. */ ApplyLauncherWakeupAtCommit(); LogicalRepWorkersWakeupAtCommit(form->oid); - - if (curtup != tup) - heap_freetuple(curtup); } /* @@ -3256,25 +3268,29 @@ AlterSubscriptionOwner(const char *name, Oid newOwnerId) HeapTuple tup; Relation rel; ObjectAddress address; - Form_pg_subscription form; rel = table_open(SubscriptionRelationId, RowExclusiveLock); - tup = SearchSysCacheCopy2(SUBSCRIPTIONNAME, ObjectIdGetDatum(MyDatabaseId), - CStringGetDatum(name)); + subid = get_subscription_oid(name, false); + if (!object_ownercheck(SubscriptionRelationId, subid, GetUserId())) + aclcheck_error(ACLCHECK_NOT_OWNER, OBJECT_SUBSCRIPTION, name); - if (!HeapTupleIsValid(tup)) - ereport(ERROR, - (errcode(ERRCODE_UNDEFINED_OBJECT), - errmsg("subscription \"%s\" does not exist", name))); + /* + * Lock the subscription so nobody else can do anything with it. Use + * get_object_address() in case the subscription was dropped or renamed + * while waiting for the lock. + */ + address = get_object_address(OBJECT_SUBSCRIPTION, + (Node *) makeString(pstrdup(name)), + NULL, AccessExclusiveLock, false); + subid = address.objectId; - form = (Form_pg_subscription) GETSTRUCT(tup); - subid = form->oid; + tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid)); + if (!HeapTupleIsValid(tup)) + elog(ERROR, "cache lookup failed for subscription %u", subid); AlterSubscriptionOwner_internal(rel, tup, newOwnerId); - ObjectAddressSet(address, SubscriptionRelationId, subid); - heap_freetuple(tup); table_close(rel, RowExclusiveLock); @@ -3290,26 +3306,44 @@ AlterSubscriptionOwner_oid(Oid subid, Oid newOwnerId) { HeapTuple tup; Relation rel; - Form_pg_subscription form; + Oid subdbid; rel = table_open(SubscriptionRelationId, RowExclusiveLock); - tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid)); + tup = SearchSysCache1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid)); if (!HeapTupleIsValid(tup)) ereport(ERROR, (errcode(ERRCODE_UNDEFINED_OBJECT), errmsg("subscription with OID %u does not exist", subid))); - form = (Form_pg_subscription) GETSTRUCT(tup); + subdbid = ((Form_pg_subscription) GETSTRUCT(tup))->subdbid; + ReleaseSysCache(tup); /* * Don't process subscriptions belonging to other databases. While * pg_subscription is a shared catalog, subscriptions refer to db-local * objects which exist only in the database identified by subdbid. */ - if (form->subdbid == MyDatabaseId) - AlterSubscriptionOwner_internal(rel, tup, newOwnerId); + if (subdbid != MyDatabaseId) + { + table_close(rel, RowExclusiveLock); + return; + } + + /* + * Lock the subscription so nobody else can do anything with it (including + * the replication workers). + */ + LockSharedObject(SubscriptionRelationId, subid, 0, AccessExclusiveLock); + + tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(subid)); + if (!HeapTupleIsValid(tup)) + ereport(ERROR, + (errcode(ERRCODE_UNDEFINED_OBJECT), + errmsg("subscription with OID %u does not exist", subid))); + + AlterSubscriptionOwner_internal(rel, tup, newOwnerId); heap_freetuple(tup); diff --git a/src/test/subscription/t/035_conflicts.pl b/src/test/subscription/t/035_conflicts.pl index 8abd7eb6d94..7f64f39ff23 100644 --- a/src/test/subscription/t/035_conflicts.pl +++ b/src/test/subscription/t/035_conflicts.pl @@ -1149,8 +1149,8 @@ $node_subscriber->safe_psql('postgres', "DROP TABLESPACE backup_space"); ############################################################################### # Check that the conflict log table can't be dropped by ALTER SUBSCRIPTION ... # SET (conflict_log_destination = 'log') unless the subscription is disabled -# and has no prepared transactions, nor by DROP SUBSCRIPTION while prepared -# transactions exist. +# and has no prepared transactions, nor can the subscription be dropped or +# have its owner changed while prepared transactions exist. ############################################################################### $node_publisher->safe_psql( 'postgres', qq[ @@ -1208,6 +1208,20 @@ like( "changing conflict_log_destination to 'log' is not allowed for enabled subscription" ); +$node_subscriber->safe_psql( + 'postgres', qq[ + CREATE ROLE regress_2pc_owner; + GRANT CREATE ON DATABASE postgres TO regress_2pc_owner; +]); + +# Fail - prepared transactions exist +($cmdret, $stdout, $stderr) = $node_subscriber->psql('postgres', + "ALTER SUBSCRIPTION sub_2pc OWNER TO regress_2pc_owner"); +like( + $stderr, + qr/ERROR: cannot change owner of subscription "sub_2pc" when prepared transactions exist/, + "changing subscription owner fails when prepared transactions exist"); + # Disable the subscription and wait for the apply worker to stop $node_subscriber->safe_psql('postgres', "ALTER SUBSCRIPTION sub_2pc DISABLE"); $node_subscriber->poll_query_until('postgres', @@ -1246,12 +1260,16 @@ is( $node_subscriber->safe_psql( '1', 'conflict recorded by the prepared transaction is committed'); -# With the subscription disabled and no prepared transactions, the conflict -# log table can be dropped. +# With the subscription disabled and no prepared transactions, changing the +# owner and dropping the conflict log table both succeed. $node_subscriber->safe_psql('postgres', "ALTER SUBSCRIPTION sub_2pc DISABLE"); $node_subscriber->poll_query_until('postgres', "SELECT count(*) = 0 FROM pg_stat_subscription WHERE subname = 'sub_2pc' AND pid IS NOT NULL" ) or die "Timed out while waiting for the apply worker to stop"; +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sub_2pc OWNER TO regress_2pc_owner"); +$node_subscriber->safe_psql('postgres', + "ALTER SUBSCRIPTION sub_2pc OWNER TO CURRENT_USER"); $node_subscriber->safe_psql('postgres', "ALTER SUBSCRIPTION sub_2pc SET (conflict_log_destination = 'log')"); is( $node_subscriber->safe_psql( @@ -1264,7 +1282,12 @@ is( $node_subscriber->safe_psql( # Clean up $node_subscriber->safe_psql('postgres', "DROP SUBSCRIPTION sub_2pc"); -$node_subscriber->safe_psql('postgres', "DROP TABLE tab_2pc"); +$node_subscriber->safe_psql( + 'postgres', qq[ + REVOKE CREATE ON DATABASE postgres FROM regress_2pc_owner; + DROP ROLE regress_2pc_owner; + DROP TABLE tab_2pc; +]); $node_publisher->safe_psql( 'postgres', qq[ DROP PUBLICATION pub_2pc; -- 2.54.0 (Apple Git-157)