From a1f9fe26045296921f002fc8999ba4bc1ba9b8bb Mon Sep 17 00:00:00 2001
From: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Date: Tue, 17 Nov 2026 10:44:17 +0000
Subject: [PATCH v1 1/2] Detect mismatched subscription and slot failover
 states

A subscription can use a manually managed slot whose failover property does not
match its failover parameter, for example after changing its slot or connection,
or recreating the slot.

For PostgreSQL 20 and later publishers, pass the expected value to pgoutput and
validate it after acquiring the slot, before decoding starts. Older publishers
retain the existing behavior and rely on the documented requirement that users
ensure the values match.

Route START_REPLICATION failures through apply error handling so disable_on_error
and apply_error_count work as expected. Document the behavior and test both
mismatch directions.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Reviewed-by:
Discussion: https://postgr.es/m/avMmtxMsgqKy4IQq@bdtpg
---
 doc/src/sgml/logicaldecoding.sgml             |  11 ++
 doc/src/sgml/monitoring.sgml                  |   8 +-
 doc/src/sgml/ref/alter_subscription.sgml      |   8 +
 doc/src/sgml/ref/create_subscription.sgml     |   8 +
 .../libpqwalreceiver/libpqwalreceiver.c       |   8 +
 src/backend/replication/logical/worker.c      |  82 +++++----
 src/backend/replication/pgoutput/pgoutput.c   |  26 +++
 src/include/replication/logicalproto.h        |   4 +
 src/include/replication/pgoutput.h            |   2 +
 src/include/replication/walreceiver.h         |   2 +
 src/test/subscription/meson.build             |   1 +
 .../subscription/t/039_slot_properties.pl     | 156 ++++++++++++++++++
 12 files changed, 284 insertions(+), 32 deletions(-)
 create mode 100644 src/test/subscription/t/039_slot_properties.pl

diff --git a/doc/src/sgml/logicaldecoding.sgml b/doc/src/sgml/logicaldecoding.sgml
index 6dc49108997..79397c7a3f1 100644
--- a/doc/src/sgml/logicaldecoding.sgml
+++ b/doc/src/sgml/logicaldecoding.sgml
@@ -740,6 +740,17 @@ DETAIL:  Synchronization could lead to data loss, because the remote slot needs
        </listitem>
       </varlistentry>
 
+      <varlistentry id="pgoutput-options-slot-failover">
+       <term><varname>slot_failover</varname> (<type>boolean</type>)</term>
+       <listitem>
+        <para>
+         Reports an error unless the selected replication slot's
+         <literal>failover</literal> property matches the specified value.
+         The slot property is checked only when this option is specified.
+        </para>
+       </listitem>
+      </varlistentry>
+
       <varlistentry id="pgoutput-options-origin">
        <term><varname>origin</varname> (<type>enum</type>)</term>
        <listitem>
diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index 445fbc9232c..15e01092d09 100644
--- a/doc/src/sgml/monitoring.sgml
+++ b/doc/src/sgml/monitoring.sgml
@@ -2592,10 +2592,10 @@ description | Waiting for a newly initialized WAL file to reach durable storage
        <structfield>apply_error_count</structfield> <type>bigint</type>
       </para>
       <para>
-       Number of times an error occurred while applying changes. Note that any
-       conflict resulting in an apply error will be counted in both
-       <literal>apply_error_count</literal> and the corresponding conflict
-       count (e.g., <literal>confl_*</literal>).
+       Number of errors reported by the apply worker while starting replication
+       or applying changes. Note that any conflict resulting in an apply error
+       will be counted in both <literal>apply_error_count</literal> and the
+       corresponding conflict count (e.g., <literal>confl_*</literal>).
       </para></entry>
      </row>
 
diff --git a/doc/src/sgml/ref/alter_subscription.sgml b/doc/src/sgml/ref/alter_subscription.sgml
index 545264e8a0a..e17516d0a65 100644
--- a/doc/src/sgml/ref/alter_subscription.sgml
+++ b/doc/src/sgml/ref/alter_subscription.sgml
@@ -327,6 +327,14 @@ ALTER SUBSCRIPTION <replaceable class="parameter">name</replaceable> RENAME TO <
       option is enabled.
      </para>
 
+     <para>
+      When the publisher is running
+      <productname>PostgreSQL</productname> 20 or later, the apply worker
+      reports an error when starting replication if the named slot's
+      <literal>failover</literal> property does not match the subscription
+      parameter.
+     </para>
+
      <para>
       The <link linkend="sql-createsubscription-params-with-failover"><literal>failover</literal></link>,
       <link linkend="sql-createsubscription-params-with-two-phase"><literal>two_phase</literal></link>, and
diff --git a/doc/src/sgml/ref/create_subscription.sgml b/doc/src/sgml/ref/create_subscription.sgml
index 92552e97009..1ee3b4d0f55 100644
--- a/doc/src/sgml/ref/create_subscription.sgml
+++ b/doc/src/sgml/ref/create_subscription.sgml
@@ -213,6 +213,14 @@ CREATE SUBSCRIPTION <replaceable class="parameter">subscription_name</replaceabl
           option is disabled or could be disabled for sync even when the
           subscription's <literal>failover</literal> option is enabled.
          </para>
+
+         <para>
+          When the publisher is running
+          <productname>PostgreSQL</productname> 20 or later, the apply worker
+          reports an error when starting replication if the named slot's
+          <literal>failover</literal> property does not match the subscription
+          parameter.
+         </para>
         </listitem>
        </varlistentry>
       </variablelist>
diff --git a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
index dcc738f4e38..e581e60b9c3 100644
--- a/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
+++ b/src/backend/replication/libpqwalreceiver/libpqwalreceiver.c
@@ -31,6 +31,7 @@
 #include "miscadmin.h"
 #include "pgstat.h"
 #include "pqexpbuffer.h"
+#include "replication/logicalproto.h"
 #include "replication/slotsync.h"
 #include "replication/walreceiver.h"
 #include "storage/latch.h"
@@ -657,6 +658,13 @@ libpqrcv_startstreaming(WalReceiverConn *conn,
 			PQserverVersion(conn->streamConn) >= 150000)
 			appendStringInfoString(&cmd, ", two_phase 'on'");
 
+		if (options->proto.logical.slot_failover_set &&
+			PQserverVersion(conn->streamConn) >=
+			LOGICALREP_SLOT_PROPERTY_CHECK_SERVER_VERSION_NUM)
+			appendStringInfo(&cmd, ", slot_failover '%s'",
+							 options->proto.logical.slot_failover ?
+							 "true" : "false");
+
 		if (options->proto.logical.origin &&
 			PQserverVersion(conn->streamConn) >= 160000)
 		{
diff --git a/src/backend/replication/logical/worker.c b/src/backend/replication/logical/worker.c
index 95044620e68..31f20703883 100644
--- a/src/backend/replication/logical/worker.c
+++ b/src/backend/replication/logical/worker.c
@@ -5675,6 +5675,8 @@ set_stream_options(WalRcvStreamOptions *options,
 	}
 
 	options->proto.logical.twophase = false;
+	options->proto.logical.slot_failover = false;
+	options->proto.logical.slot_failover_set = false;
 	options->proto.logical.origin = pstrdup(MySubscription->origin);
 }
 
@@ -5693,6 +5695,36 @@ cleanup_subxact_info(void)
 	subxact_data.nsubxacts_max = 0;
 }
 
+/*
+ * Handle an error encountered while starting or running apply.
+ *
+ * This is only for use in error handler code.
+ */
+static void
+handle_apply_error(void)
+{
+	/*
+	 * Reset the origin state to prevent the advancement of origin progress if
+	 * we fail to apply. Otherwise, this will result in transaction loss as
+	 * that transaction won't be sent again by the server.
+	 */
+	replorigin_xact_clear(true);
+
+	if (MySubscription->disableonerr)
+		DisableSubscriptionAndExit();
+	else
+	{
+		/*
+		 * Report the worker failed while applying changes. Abort the current
+		 * transaction so that the stats message is sent in an idle state.
+		 */
+		AbortOutOfAnyTransaction();
+		pgstat_report_subscription_error(MySubscription->oid);
+
+		PG_RE_THROW();
+	}
+}
+
 /*
  * Common function to run the apply loop with error handling. Disable the
  * subscription, if necessary.
@@ -5709,28 +5741,7 @@ start_apply(XLogRecPtr origin_startpos)
 	}
 	PG_CATCH();
 	{
-		/*
-		 * Reset the origin state to prevent the advancement of origin
-		 * progress if we fail to apply. Otherwise, this will result in
-		 * transaction loss as that transaction won't be sent again by the
-		 * server.
-		 */
-		replorigin_xact_clear(true);
-
-		if (MySubscription->disableonerr)
-			DisableSubscriptionAndExit();
-		else
-		{
-			/*
-			 * Report the worker failed while applying changes. Abort the
-			 * current transaction so that the stats message is sent in an
-			 * idle state.
-			 */
-			AbortOutOfAnyTransaction();
-			pgstat_report_subscription_error(MySubscription->oid);
-
-			PG_RE_THROW();
-		}
+		handle_apply_error();
 	}
 	PG_END_TRY();
 }
@@ -5751,6 +5762,7 @@ run_apply_worker(void)
 	TimeLineID	startpointTLI;
 	char	   *err;
 	bool		must_use_password;
+	bool		enable_twophase;
 
 	slotname = MySubscription->slotname;
 
@@ -5815,6 +5827,13 @@ run_apply_worker(void)
 
 	set_stream_options(&options, slotname, &origin_startpos);
 
+	enable_twophase =
+		MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_PENDING &&
+		AllTablesyncsReady();
+
+	options.proto.logical.slot_failover = MySubscription->failover;
+	options.proto.logical.slot_failover_set = true;
+
 	/*
 	 * Even when the two_phase mode is requested by the user, it remains as
 	 * the tri-state PENDING until all tablesyncs have reached READY state.
@@ -5824,13 +5843,24 @@ run_apply_worker(void)
 	 * PENDING, which allows ALTER SUBSCRIPTION ... REFRESH PUBLICATION to
 	 * work.
 	 */
-	if (MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_PENDING &&
-		AllTablesyncsReady())
+	if (enable_twophase)
 	{
 		/* Start streaming with two_phase enabled */
 		options.proto.logical.twophase = true;
+	}
+
+	PG_TRY();
+	{
 		walrcv_startstreaming(LogRepWorkerWalRcvConn, &options);
+	}
+	PG_CATCH();
+	{
+		handle_apply_error();
+	}
+	PG_END_TRY();
 
+	if (enable_twophase)
+	{
 		StartTransactionCommand();
 
 		/*
@@ -5844,10 +5874,6 @@ run_apply_worker(void)
 		PopActiveSnapshot();
 		CommitTransactionCommand();
 	}
-	else
-	{
-		walrcv_startstreaming(LogRepWorkerWalRcvConn, &options);
-	}
 
 	ereport(DEBUG1,
 			(errmsg_internal("logical replication apply worker for subscription \"%s\" two_phase is %s",
diff --git a/src/backend/replication/pgoutput/pgoutput.c b/src/backend/replication/pgoutput/pgoutput.c
index 57b3ccbed60..6258b96b11d 100644
--- a/src/backend/replication/pgoutput/pgoutput.c
+++ b/src/backend/replication/pgoutput/pgoutput.c
@@ -296,6 +296,7 @@ parse_output_parameters(List *options, PGOutputData *data)
 	bool		messages_option_given = false;
 	bool		streaming_given = false;
 	bool		two_phase_option_given = false;
+	bool		slot_failover_option_given = false;
 	bool		origin_option_given = false;
 
 	/* Initialize optional parameters to defaults */
@@ -303,6 +304,8 @@ parse_output_parameters(List *options, PGOutputData *data)
 	data->streaming = LOGICALREP_STREAM_OFF;
 	data->messages = false;
 	data->two_phase = false;
+	data->slot_failover = false;
+	data->slot_failover_set = false;
 	data->publish_no_origin = false;
 
 	foreach(lc, options)
@@ -396,6 +399,17 @@ parse_output_parameters(List *options, PGOutputData *data)
 
 			data->two_phase = defGetBoolean(defel);
 		}
+		else if (strcmp(defel->defname, "slot_failover") == 0)
+		{
+			if (slot_failover_option_given)
+				ereport(ERROR,
+						(errcode(ERRCODE_SYNTAX_ERROR),
+						 errmsg("conflicting or redundant options")));
+			slot_failover_option_given = true;
+
+			data->slot_failover = defGetBoolean(defel);
+			data->slot_failover_set = true;
+		}
 		else if (strcmp(defel->defname, "origin") == 0)
 		{
 			char	   *origin;
@@ -550,6 +564,18 @@ pgoutput_startup(LogicalDecodingContext *ctx, OutputPluginOptions *opt,
 		else
 			ctx->twophase_opt_given = true;
 
+		if (data->slot_failover_set &&
+			data->slot_failover != MyReplicationSlot->data.failover)
+			ereport(ERROR,
+					(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
+					 errmsg("replication slot \"%s\" has failover %s",
+							NameStr(MyReplicationSlot->data.name),
+							MyReplicationSlot->data.failover ?
+							"enabled" : "disabled"),
+					 errdetail("The expected failover setting is %s.",
+							   data->slot_failover ?
+							   "enabled" : "disabled")));
+
 		/* Init publication state. */
 		data->publications = NIL;
 		publications_valid = false;
diff --git a/src/include/replication/logicalproto.h b/src/include/replication/logicalproto.h
index 058a955e20c..c1aaaf6789a 100644
--- a/src/include/replication/logicalproto.h
+++ b/src/include/replication/logicalproto.h
@@ -36,6 +36,9 @@
  * LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM is the minimum protocol version
  * where we support applying large streaming transactions in parallel.
  * Introduced in PG16.
+ *
+ * LOGICALREP_SLOT_PROPERTY_CHECK_SERVER_VERSION_NUM is the minimum server
+ * version that can check slot properties during START_REPLICATION.
  */
 #define LOGICALREP_PROTO_MIN_VERSION_NUM 1
 #define LOGICALREP_PROTO_VERSION_NUM 1
@@ -43,6 +46,7 @@
 #define LOGICALREP_PROTO_TWOPHASE_VERSION_NUM 3
 #define LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM 4
 #define LOGICALREP_PROTO_MAX_VERSION_NUM LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM
+#define LOGICALREP_SLOT_PROPERTY_CHECK_SERVER_VERSION_NUM 200000
 
 /*
  * Logical message types
diff --git a/src/include/replication/pgoutput.h b/src/include/replication/pgoutput.h
index 774ebe53fa4..41d2be1be3c 100644
--- a/src/include/replication/pgoutput.h
+++ b/src/include/replication/pgoutput.h
@@ -33,6 +33,8 @@ typedef struct PGOutputData
 	char		streaming;
 	bool		messages;
 	bool		two_phase;
+	bool		slot_failover;
+	bool		slot_failover_set;
 	bool		publish_no_origin;
 } PGOutputData;
 
diff --git a/src/include/replication/walreceiver.h b/src/include/replication/walreceiver.h
index 5cfe90f9989..36afc96553d 100644
--- a/src/include/replication/walreceiver.h
+++ b/src/include/replication/walreceiver.h
@@ -186,6 +186,8 @@ typedef struct
 			char	   *streaming_str;	/* Streaming of large transactions */
 			bool		twophase;	/* Streaming of two-phase transactions at
 									 * prepare time */
+			bool		slot_failover;	/* Expected slot failover state */
+			bool		slot_failover_set;	/* Check slot failover state */
 			char	   *origin; /* Only publish data originating from the
 								 * specified origin */
 		}			logical;
diff --git a/src/test/subscription/meson.build b/src/test/subscription/meson.build
index e71e95c6297..8b15df814c8 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_slot_properties.pl',
       't/100_bugs.pl',
     ],
   },
diff --git a/src/test/subscription/t/039_slot_properties.pl b/src/test/subscription/t/039_slot_properties.pl
new file mode 100644
index 00000000000..b771b5b493e
--- /dev/null
+++ b/src/test/subscription/t/039_slot_properties.pl
@@ -0,0 +1,156 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Test validation of subscription and replication slot properties.
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+my $publisher = PostgreSQL::Test::Cluster->new('publisher');
+$publisher->init(allows_streaming => 'logical');
+$publisher->start;
+
+my $subscriber = PostgreSQL::Test::Cluster->new('subscriber');
+$subscriber->init;
+$subscriber->start;
+
+my $publisher_connstr = $publisher->connstr . ' dbname=postgres';
+
+# Recreate a logical slot with the requested failover property.
+sub recreate_slot
+{
+	my ($slot_name, $failover) = @_;
+
+	$publisher->safe_psql(
+		'postgres', qq[
+		SELECT pg_drop_replication_slot('$slot_name')
+		WHERE EXISTS (
+			SELECT FROM pg_replication_slots WHERE slot_name = '$slot_name');
+		SELECT pg_create_logical_replication_slot(
+			'$slot_name', 'pgoutput', false, false, $failover);
+	]);
+}
+
+# Wait until the apply worker has released a slot.
+sub wait_for_slot_inactive
+{
+	my ($slot_name) = @_;
+
+	$publisher->poll_query_until(
+		'postgres', qq[
+		SELECT active_pid IS NULL
+		FROM pg_replication_slots
+		WHERE slot_name = '$slot_name';
+	]) or die "timed out waiting for slot $slot_name to become inactive";
+}
+
+$publisher->safe_psql(
+	'postgres', q[
+	CREATE TABLE property_tab (a integer PRIMARY KEY, payload text);
+	CREATE PUBLICATION property_pub FOR TABLE property_tab;
+]);
+
+$subscriber->safe_psql(
+	'postgres', q[
+	CREATE TABLE property_tab (a integer PRIMARY KEY, payload text);
+]);
+
+# A failover-enabled subscription requires a failover-enabled slot.
+recreate_slot('failover_slot', 'true');
+$subscriber->safe_psql(
+	'postgres', qq[
+	CREATE SUBSCRIPTION failover_sub
+	CONNECTION '$publisher_connstr application_name=failover_sub'
+	PUBLICATION property_pub
+	WITH (slot_name = 'failover_slot', create_slot = false,
+		  copy_data = false, enabled = false, failover = true,
+		  disable_on_error = true);
+	ALTER SUBSCRIPTION failover_sub ENABLE;
+]);
+
+$publisher->poll_query_until(
+	'postgres', q[
+	SELECT active AND failover
+	FROM pg_replication_slots
+	WHERE slot_name = 'failover_slot';
+]) or die 'timed out waiting for the failover slot to become active';
+
+$subscriber->safe_psql('postgres', 'ALTER SUBSCRIPTION failover_sub DISABLE');
+wait_for_slot_inactive('failover_slot');
+recreate_slot('failover_slot', 'false');
+
+my $subscriber_log_offset = -s $subscriber->logfile;
+$subscriber->safe_psql('postgres', 'ALTER SUBSCRIPTION failover_sub ENABLE');
+$subscriber->wait_for_log(
+	qr/replication slot "failover_slot" has failover disabled/,
+	$subscriber_log_offset);
+
+$subscriber->poll_query_until(
+	'postgres', q[
+	SELECT NOT subenabled
+	FROM pg_subscription
+	WHERE subname = 'failover_sub';
+]) or die 'timed out waiting for failover_sub to be disabled';
+
+$subscriber->poll_query_until(
+	'postgres', q[
+	SELECT apply_error_count > 0
+	FROM pg_stat_subscription_stats
+	WHERE subname = 'failover_sub';
+]) or die 'timed out waiting for the apply error to be counted';
+
+wait_for_slot_inactive('failover_slot');
+$subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION failover_sub');
+
+# A subscription without failover enabled must reject a failover-enabled slot.
+recreate_slot('extra_failover_slot', 'true');
+$subscriber->safe_psql(
+	'postgres', qq[
+	CREATE SUBSCRIPTION extra_failover_sub
+	CONNECTION '$publisher_connstr application_name=extra_failover_sub'
+	PUBLICATION property_pub
+	WITH (slot_name = 'extra_failover_slot', create_slot = false,
+		  copy_data = false, enabled = false, failover = false,
+		  disable_on_error = true);
+]);
+
+$subscriber_log_offset = -s $subscriber->logfile;
+$subscriber->safe_psql('postgres',
+	'ALTER SUBSCRIPTION extra_failover_sub ENABLE');
+$subscriber->wait_for_log(
+	qr/replication slot "extra_failover_slot" has failover enabled/,
+	$subscriber_log_offset);
+
+$subscriber->poll_query_until(
+	'postgres', q[
+	SELECT NOT subenabled
+	FROM pg_subscription
+	WHERE subname = 'extra_failover_sub';
+]) or die 'timed out waiting for extra_failover_sub to be disabled';
+
+$subscriber->poll_query_until(
+	'postgres', q[
+	SELECT apply_error_count > 0
+	FROM pg_stat_subscription_stats
+	WHERE subname = 'extra_failover_sub';
+]) or die 'timed out waiting for the apply error to be counted';
+
+is( $subscriber->safe_psql(
+		'postgres', q[
+		SELECT NOT subenabled AND apply_error_count > 0
+		FROM pg_subscription
+		JOIN pg_stat_subscription_stats
+		  ON subid = pg_subscription.oid
+		WHERE pg_subscription.subname = 'extra_failover_sub';
+	]),
+	't',
+	'failover mismatch disabled the subscription and counted an apply error');
+
+wait_for_slot_inactive('extra_failover_slot');
+$subscriber->safe_psql('postgres', 'DROP SUBSCRIPTION extra_failover_sub');
+
+$subscriber->stop;
+$publisher->stop;
+
+done_testing();
-- 
2.47.3

