Hi,

On Wed, Nov18, 2026 at 10:15 PM Bertrand Drouvot wrote:

On Mon, Nov 16, 2026 at 03:46:25PM +0530, Amit Kapila wrote:
> On Tue, Nov 10, 2026 at 7:44 PM Bertrand Drouvot
> > For failover, the value should match exactly.
> >
> > For two_phase, the expected value depends on subtwophasestate:
> >
> > • DISABLED: the slot must have two_phase = false.
> > • PENDING, before the tables are ready: it must remain false.
> > • PENDING, once the tables are ready: either value can be accepted before 
enabling
> > it and recording the state as ENABLED. This also makes the
> > transition safe if the worker previously exited between those two
> > operations.
> > • ENABLED: the slot must have two_phase = true.
> >
>
> Instead of PENDING state checks, how about checking mismatch in
> begin_prepared kind of functions whether the subscription has
> reached ENABLED state? I am asking this because if the slot is
> initially created with two_phase = true and the subscription is in
> pending state then the apply worker will start receiving prepared
> transactions and will lead to problems described under "TWO_PHASE
> TRANSACTIONS" in worker.c.

Thanks for looking at it!

I think that could be too late. With parallel streaming, a parallel
apply worker may already have executed the transaction's changes.


IIUC, it wouldn't be too late. Even if the changes are already being executed, the transaction won't be prepared if we catch the mismatch in apply_handle_prepare (and related functions). The user can still recover by disabling two_phase on the slot, and the transaction will then be replicated again as a normal transaction once COMMIT PREPARED is executed on the publisher.

Also, catching this in the apply_handle_* functions still protects cases where the publisher is on an older version that does not support the new protocol option. It can also serve as a useful safeguard against non-standard servers that might accidentally send unexpected prepared transactions (similar checks were added in fe6a20c), and we already have related checks that disallow prepare messages in the tablesync worker. So adding a runtime check seems like an independent win to me.

Or do you have scenarios in mind that the runtime check cannot handle that I might be missing (for cases when two_phase is disabled on sub but enabled on slot) ?

I am attaching a draft patch that adds runtime check with a test to show that reporting an ERROR at that point is recoverable, just for reference and discussion.

--
Best Regards,
Zhijie Hou
From e0f8987ab75f388fdceb12e10635ce33a3ec5502 Mon Sep 17 00:00:00 2001
From: Zhijie Hou <[email protected]>
Date: Thu, 19 Nov 2026 14:24:20 +0800
Subject: [PATCH] Reject two-phase transactions when two_phase is not enabled.

A subscription using a manually created or replacement replication slot
can receive two-phase transactions from the publisher while its own
two_phase state is still disabled or pending. When disabled, the
subscriber applies prepared transactions that it was not configured to
receive. When pending, initial table synchronization may still be in
progress, so the apply worker skips changes for tables being
synchronized and prepares empty transactions, losing those changes when
COMMIT PREPARED is later replayed.

Fix this by verifying that the subscription's two_phase state is enabled
before handling BEGIN PREPARE, PREPARE, STREAM PREPARE, COMMIT PREPARED,
or ROLLBACK PREPARED messages, and raising an error otherwise. Even if
streamed changes have begun executing in a parallel apply worker,
rejecting STREAM PREPARE aborts the uncommitted changes before the
transaction can be prepared. Users can recover by disabling two_phase on
the slot via ALTER SUBSCRIPTION ... SET (two_phase = false), allowing
any pending prepared transaction to replicate as a normal transaction
once committed on the publisher.

---
 src/backend/replication/logical/worker.c      | 45 ++++++++++----
 .../subscription/t/023_twophase_stream.pl     | 60 +++++++++++++++++++
 2 files changed, 94 insertions(+), 11 deletions(-)

diff --git a/src/backend/replication/logical/worker.c 
b/src/backend/replication/logical/worker.c
index 95044620e68..eac859dc197 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -1292,6 +1292,31 @@ apply_handle_commit(StringInfo s)
        reset_apply_remote_context();
 }
 
+/*
+ * Verify that the subscription is ready to apply two-phase transactions.
+ *
+ * Reject two-phase messages while the subscription's two_phase state is
+ * DISABLED or PENDING, so we do not apply unexpected prepared transactions or
+ * prepare empty transactions while initial table synchronization is in
+ * progress.
+ */
+static void
+check_two_phase_state(void)
+{
+       /* Tablesync should never receive two-phase messages. */
+       if (am_tablesync_worker())
+               ereport(ERROR,
+                               (errcode(ERRCODE_PROTOCOL_VIOLATION),
+                                errmsg_internal("tablesync worker received a 
%s message",
+                                                                
logicalrep_message_type(remote_ctx.command))));
+
+       if (MySubscription->twophasestate != LOGICALREP_TWOPHASE_STATE_ENABLED)
+               ereport(ERROR,
+                               
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+                                errmsg("cannot apply two-phase transaction 
when two_phase is not enabled on subscription \"%s\"",
+                                               MySubscription->name)));
+}
+
 /*
  * Handle BEGIN PREPARE message.
  */
@@ -1300,11 +1325,7 @@ apply_handle_begin_prepare(StringInfo s)
 {
        LogicalRepPreparedTxnData begin_data;
 
-       /* Tablesync should never receive prepare. */
-       if (am_tablesync_worker())
-               ereport(ERROR,
-                               (errcode(ERRCODE_PROTOCOL_VIOLATION),
-                                errmsg_internal("tablesync worker received a 
BEGIN PREPARE message")));
+       check_two_phase_state();
 
        /* There must not be an active streaming transaction. */
        Assert(!TransactionIdIsValid(stream_xid));
@@ -1364,6 +1385,8 @@ apply_handle_prepare(StringInfo s)
 {
        LogicalRepPreparedTxnData prepare_data;
 
+       check_two_phase_state();
+
        logicalrep_read_prepare(s, &prepare_data);
 
        if (prepare_data.prepare_lsn != remote_ctx.finish_lsn)
@@ -1439,6 +1462,8 @@ apply_handle_commit_prepared(StringInfo s)
        LogicalRepCommitPreparedTxnData prepare_data;
        char            gid[GIDSIZE];
 
+       check_two_phase_state();
+
        logicalrep_read_commit_prepared(s, &prepare_data);
        set_remote_transaction_info(prepare_data.xid, prepare_data.commit_lsn);
 
@@ -1491,6 +1516,8 @@ apply_handle_rollback_prepared(StringInfo s)
        LogicalRepRollbackPreparedTxnData rollback_data;
        char            gid[GIDSIZE];
 
+       check_two_phase_state();
+
        logicalrep_read_rollback_prepared(s, &rollback_data);
        set_remote_transaction_info(rollback_data.xid, 
rollback_data.rollback_end_lsn);
 
@@ -1556,17 +1583,13 @@ apply_handle_stream_prepare(StringInfo s)
        /* Save the message before it is consumed. */
        StringInfoData original_msg = *s;
 
+       check_two_phase_state();
+
        if (in_streamed_transaction)
                ereport(ERROR,
                                (errcode(ERRCODE_PROTOCOL_VIOLATION),
                                 errmsg_internal("STREAM PREPARE message 
without STREAM STOP")));
 
-       /* Tablesync should never receive prepare. */
-       if (am_tablesync_worker())
-               ereport(ERROR,
-                               (errcode(ERRCODE_PROTOCOL_VIOLATION),
-                                errmsg_internal("tablesync worker received a 
STREAM PREPARE message")));
-
        logicalrep_read_stream_prepare(s, &prepare_data);
        set_remote_transaction_info(prepare_data.xid, prepare_data.prepare_lsn);
 
diff --git a/src/test/subscription/t/023_twophase_stream.pl 
b/src/test/subscription/t/023_twophase_stream.pl
index fbb2dffbd95..b75cfe6c8ce 100644
--- a/src/test/subscription/t/023_twophase_stream.pl
+++ b/src/test/subscription/t/023_twophase_stream.pl
@@ -472,6 +472,66 @@ $result =
   $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM test_tab_2");
 is($result, qq(2), 'transaction is committed on subscriber after retrying');
 
+###############################
+# Verify that a prepared transaction from a two_phase-enabled slot is rejected
+# when two_phase is disabled on the subscription, and that disabling two_phase
+# on the slot recovers replication.
+###############################
+$node_subscriber->safe_psql('postgres', "ALTER SUBSCRIPTION tap_sub DISABLE");
+$node_subscriber->poll_query_until(
+       'postgres', q{
+       SELECT count(*) = 0 FROM pg_stat_activity
+       WHERE backend_type LIKE 'logical replication%worker';
+}) or die "Timed out while waiting for logical replication workers to stop";
+
+$node_subscriber->safe_psql(
+       'postgres', q{
+       ALTER SUBSCRIPTION tap_sub
+       SET (two_phase = false, disable_on_error = true);
+});
+$node_publisher->psql(
+       'postgres',
+       "ALTER_REPLICATION_SLOT tap_sub (two_phase true);",
+       replication => 'database');
+
+$offset = -s $node_subscriber->logfile;
+$node_subscriber->safe_psql('postgres', "ALTER SUBSCRIPTION tap_sub ENABLE");
+$node_publisher->safe_psql(
+       'postgres', q{
+       BEGIN;
+       INSERT INTO test_tab_2 VALUES (3);
+       PREPARE TRANSACTION 'xact_mismatch';
+});
+
+$node_subscriber->wait_for_log(
+       qr/cannot apply two-phase transaction when two_phase is not enabled/,
+       $offset);
+$node_subscriber->poll_query_until(
+       'postgres', q{
+       SELECT NOT subenabled FROM pg_subscription WHERE subname = 'tap_sub'
+       AND NOT EXISTS (
+               SELECT 1 FROM pg_stat_activity
+               WHERE backend_type LIKE 'logical replication%worker');
+}) or die "Timed out while waiting for tap_sub to be disabled";
+
+$result = $node_subscriber->safe_psql('postgres',
+       "SELECT count(*) FROM pg_prepared_xacts");
+is($result, qq(0), 'prepared transaction rejected when two_phase disabled');
+
+# Recover by disabling two_phase on the slot and verify the transaction
+# replicates as a normal transaction once committed on the publisher.
+$node_subscriber->safe_psql(
+       'postgres', q{
+       ALTER SUBSCRIPTION tap_sub SET (two_phase = false);
+       ALTER SUBSCRIPTION tap_sub ENABLE;
+});
+$node_publisher->safe_psql('postgres', "COMMIT PREPARED 'xact_mismatch'");
+$node_publisher->wait_for_catchup($appname);
+
+$result =
+  $node_subscriber->safe_psql('postgres', "SELECT count(*) FROM test_tab_2");
+is($result, qq(3), 'prepared transaction replicated after recovery');
+
 ###############################
 # check all the cleanup
 ###############################
-- 
2.54.0 (Apple Git-157)

Reply via email to