Patch
Refuse DROP SUBSCRIPTION while prepared transactions remain.
- Branch
- REL_16_STABLE
- Risk
- –
- Base commit
- be913fabe79d73a37af55eafc3d3352db4c3d1ca
To apply it to a checkout of REL_16_STABLE at the base commit:
curl -s https://ai-annex.j-davis.com/api/v1/patches/01a1cbef-c7a2-7572-8b0a-f39ee8f17a09 | jq -r .body | git am
From 214c64763aab8a7c30e54467510b0ccb4d54bdbe Mon Sep 17 00:00:00 2001
From: Grok <grok@x.ai>
Date: Wed, 11 Nov 2026 10:44:13 -0800
Subject: [PATCH] Refuse DROP SUBSCRIPTION while prepared transactions remain.
Dropping a two_phase subscription stopped its apply worker and removed
its replication slot without looking for prepared transactions the
worker had created. Those transactions stayed in pg_prepared_xacts,
kept their locks, and held back the xmin horizon. A later COMMIT
PREPARED or ROLLBACK PREPARED on the publisher was never applied.
Reject that state from DROP SUBSCRIPTION after the workers have been
stopped and before any non-transactional cleanup. This branch has no
LookupGXactBySubid, so add one in twophase.c.
---
doc/src/sgml/ref/drop_subscription.sgml | 22 +++++++
src/backend/access/transam/twophase.c | 84 +++++++++++++++++++++++++
src/backend/commands/subscriptioncmds.c | 16 +++++
src/include/access/twophase.h | 1 +
src/test/subscription/t/021_twophase.pl | 40 ++++++++++++
5 files changed, 163 insertions(+)
diff --git a/doc/src/sgml/ref/drop_subscription.sgml b/doc/src/sgml/ref/drop_subscription.sgml
index 66bbdd93ddd..7dfa20ef59e 100644
--- a/doc/src/sgml/ref/drop_subscription.sgml
+++ b/doc/src/sgml/ref/drop_subscription.sgml
@@ -114,6 +114,28 @@ DROP SUBSCRIPTION [ IF EXISTS ] <replaceable class="parameter">name</replaceable
If a subscription is associated with a replication slot, then <command>DROP
SUBSCRIPTION</command> cannot be executed inside a transaction block.
</para>
+
+ <para>
+ <command>DROP SUBSCRIPTION</command> cannot be executed while the
+ subscription still has prepared transactions created by its logical
+ replication worker. That is the case when
+ <link linkend="sql-createsubscription-with-two-phase"><literal>two_phase</literal></link>
+ is enabled and a transaction has been prepared on the publisher but not
+ yet committed or rolled back. The worker that would apply the
+ corresponding <command>COMMIT PREPARED</command> or
+ <command>ROLLBACK PREPARED</command> is stopped by this command, and any
+ associated replication slot is dropped, so those transactions would
+ otherwise remain prepared. They keep their locks and hold back the
+ transaction ID horizon until somebody resolves them manually. Commit or
+ roll them back on the publisher and let the subscriber apply that, or
+ commit or roll them back directly on the subscriber, and then try again.
+ Transactions prepared by the logical replication worker for this
+ subscription have identifiers of the form
+ <quote><literal>pg_gid_%u_%u</literal></quote> (subscription
+ <parameter>oid</parameter>, remote transaction <parameter>xid</parameter>).
+ See
+ <link linkend="view-pg-prepared-xacts"><structname>pg_prepared_xacts</structname></link>.
+ </para>
</refsect1>
<refsect1>
diff --git a/src/backend/access/transam/twophase.c b/src/backend/access/transam/twophase.c
index ec7e66c64de..cdafa8f2fc9 100644
--- a/src/backend/access/transam/twophase.c
+++ b/src/backend/access/transam/twophase.c
@@ -2705,3 +2705,87 @@ LookupGXact(const char *gid, XLogRecPtr prepare_end_lsn,
LWLockRelease(TwoPhaseStateLock);
return found;
}
+
+/*
+ * TwoPhaseTransactionGid
+ * Form the prepared transaction GID for two_phase transactions.
+ *
+ * Return the GID in the supplied buffer.
+ *
+ * This is a local copy of the helper in logical/worker.c. That copy is
+ * static, and this one stays static so the two translation units do not
+ * collide.
+ */
+static void
+TwoPhaseTransactionGid(Oid subid, TransactionId xid, char *gid_res, int szgid)
+{
+ Assert(OidIsValid(subid));
+
+ if (!TransactionIdIsValid(xid))
+ ereport(ERROR,
+ (errcode(ERRCODE_PROTOCOL_VIOLATION),
+ errmsg_internal("invalid two-phase transaction ID")));
+
+ snprintf(gid_res, szgid, "pg_gid_%u_%u", subid, xid);
+}
+
+/*
+ * IsTwoPhaseTransactionGidForSubid
+ * Check whether the given GID (as formed by TwoPhaseTransactionGid) is
+ * for the specified 'subid'.
+ */
+static bool
+IsTwoPhaseTransactionGidForSubid(Oid subid, char *gid)
+{
+ int ret;
+ Oid subid_from_gid;
+ TransactionId xid_from_gid;
+ char gid_tmp[GIDSIZE];
+
+ /* Extract the subid and xid from the given GID */
+ ret = sscanf(gid, "pg_gid_%u_%u", &subid_from_gid, &xid_from_gid);
+
+ /*
+ * Check that the given GID has expected format, and at least the subid
+ * matches.
+ */
+ if (ret != 2 || subid != subid_from_gid)
+ return false;
+
+ /*
+ * Reconstruct a temporary GID based on the subid and xid extracted from
+ * the given GID and check whether the temporary GID and the given GID
+ * match.
+ */
+ TwoPhaseTransactionGid(subid, xid_from_gid, gid_tmp, sizeof(gid_tmp));
+
+ return strcmp(gid, gid_tmp) == 0;
+}
+
+/*
+ * LookupGXactBySubid
+ * Check if the prepared transaction done by apply worker exists.
+ */
+bool
+LookupGXactBySubid(Oid subid)
+{
+ int i;
+ bool found = false;
+
+ LWLockAcquire(TwoPhaseStateLock, LW_SHARED);
+ for (i = 0; i < TwoPhaseState->numPrepXacts; i++)
+ {
+ GlobalTransaction gxact = TwoPhaseState->prepXacts[i];
+
+ /* Ignore not-yet-valid GIDs. */
+ if (gxact->valid &&
+ IsTwoPhaseTransactionGidForSubid(subid, gxact->gid))
+ {
+ found = true;
+ break;
+ }
+ }
+ LWLockRelease(TwoPhaseStateLock);
+
+ return found;
+}
diff --git a/src/backend/commands/subscriptioncmds.c b/src/backend/commands/subscriptioncmds.c
index 7e064d665d0..1a792a69072 100644
--- a/src/backend/commands/subscriptioncmds.c
+++ b/src/backend/commands/subscriptioncmds.c
@@ -16,6 +16,7 @@
#include "access/htup_details.h"
#include "access/table.h"
+#include "access/twophase.h"
#include "access/xact.h"
#include "catalog/catalog.h"
#include "catalog/dependency.h"
@@ -1629,6 +1630,21 @@ DropSubscription(DropSubscriptionStmt *stmt, bool isTopLevel)
}
list_free(subworkers);
+ /*
+ * Do not drop the subscription while prepared transactions it created are
+ * still open. The apply worker is what commits or rolls them back, and
+ * it has just been stopped. Leaving them would keep their locks and hold
+ * back the xmin horizon, and a later COMMIT PREPARED or ROLLBACK PREPARED
+ * on the publisher would no longer be applied. Workers are stopped, so
+ * no new prepare can appear before this check.
+ */
+ if (LookupGXactBySubid(subid))
+ ereport(ERROR,
+ (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+ errmsg("cannot drop subscription \"%s\" when prepared transactions exist",
+ subname),
+ errhint("Resolve these transactions and try again.")));
+
/*
* Remove the no-longer-useful entry in the launcher's table of apply
* worker start times.
diff --git a/src/include/access/twophase.h b/src/include/access/twophase.h
index 21e2af7387b..3d97d0702e7 100644
--- a/src/include/access/twophase.h
+++ b/src/include/access/twophase.h
@@ -62,4 +62,5 @@ extern void PrepareRedoRemove(TransactionId xid, bool giveWarning);
extern void restoreTwoPhaseData(void);
extern bool LookupGXact(const char *gid, XLogRecPtr prepare_end_lsn,
TimestampTz origin_prepare_timestamp);
+extern bool LookupGXactBySubid(Oid subid);
#endif /* TWOPHASE_H */
diff --git a/src/test/subscription/t/021_twophase.pl b/src/test/subscription/t/021_twophase.pl
index 803b91e9f9d..f7622c2a770 100644
--- a/src/test/subscription/t/021_twophase.pl
+++ b/src/test/subscription/t/021_twophase.pl
@@ -427,6 +427,46 @@ $result =
$node_subscriber->safe_psql('postgres', "SELECT count(*) FROM tab_copy;");
is($result, qq(2), 'replicated data in subscriber table');
+###############################
+# DROP SUBSCRIPTION must not orphan prepared transactions.
+###############################
+my $drop_sub_oid = $node_subscriber->safe_psql('postgres',
+ "SELECT oid FROM pg_subscription WHERE subname = 'tap_sub_copy';");
+
+$node_publisher->safe_psql(
+ 'postgres', qq{
+ BEGIN;
+ INSERT INTO tab_copy VALUES (101);
+ PREPARE TRANSACTION 'drop_sub_gid';
+ });
+
+$node_subscriber->poll_query_until('postgres',
+ "SELECT count(*) = 1 FROM pg_prepared_xacts WHERE gid LIKE 'pg_gid_${drop_sub_oid}\\_%'")
+ or die "timed out waiting for prepared transaction before drop";
+
+my ($stdout, $stderr);
+
+($result, $stdout, $stderr) = $node_subscriber->psql('postgres',
+ "DROP SUBSCRIPTION tap_sub_copy;");
+like(
+ $stderr,
+ qr/cannot drop subscription "tap_sub_copy" when prepared transactions exist/,
+ 'DROP SUBSCRIPTION fails while prepared transactions exist');
+
+$result = $node_subscriber->safe_psql('postgres',
+ "SELECT count(*) FROM pg_prepared_xacts WHERE gid LIKE 'pg_gid_${drop_sub_oid}\\_%';");
+is($result, qq(1), 'prepared transaction survives failed drop');
+
+$result = $node_subscriber->safe_psql('postgres',
+ "SELECT count(*) FROM pg_subscription WHERE subname = 'tap_sub_copy';");
+is($result, qq(1), 'subscription remains after failed drop');
+
+# Resolve on the publisher. The apply worker must still be able to finish it.
+$node_publisher->safe_psql('postgres', "ROLLBACK PREPARED 'drop_sub_gid';");
+$node_subscriber->poll_query_until('postgres',
+ "SELECT count(*) = 0 FROM pg_prepared_xacts WHERE gid LIKE 'pg_gid_${drop_sub_oid}\\_%'")
+ or die "timed out waiting for prepared transaction to be rolled back";
+
$node_subscriber->safe_psql('postgres', "DROP SUBSCRIPTION tap_sub_copy;");
$node_publisher->safe_psql('postgres', "DROP PUBLICATION tap_pub_copy;");
base-commit: be913fabe79d73a37af55eafc3d3352db4c3d1ca
--
2.53.0