From 58e261be66ef1698d24ba78535800b5922a666cf Mon Sep 17 00:00:00 2001
From: Jesper St John <jesper@stjohn.se>
Date: Mon, 23 Nov 2026 09:51:09 +0100
Subject: [PATCH v6] pg_basebackup: Create the WAL streaming slot before
 starting the backup

With --wal-method=stream, pg_basebackup created its replication slot only
after BASE_BACKUP had returned the backup's start position.  A checkpoint
running in between could remove WAL from that position onwards, and the
backup then failed with "requested WAL segment ... has already been
removed".

Open the WAL streaming connection and create a temporary slot on it
before sending BASE_BACKUP.  With --create-slot, the permanent slot is
still created after BASE_BACKUP has returned, so the backup's checkpoint
cannot invalidate it and a failed backup does not leave it behind; the
temporary slot is then dropped.  With --no-slot, or with --slot naming
an existing slot, nothing changes.

The connection is idle until the backup's checkpoint has completed, so
disable idle_session_timeout on it.  That checkpoint can still terminate
the connection if the temporary slot is past max_slot_wal_keep_size or
idle_replication_slot_timeout, which drops the slot.  If the connection
was lost, warn, reconnect and create the slot again before streaming
starts; the checkpoint should keep the WAL from the start position.

Document under --wal-method=stream.

Add a TAP test, which needs injection points, checking that the backup
succeeds when a checkpoint removes WAL while the slot is being created,
and when its own checkpoint terminates the connection because of
max_slot_wal_keep_size.  It also checks that the connection is opened
early only when a slot is created, and that it survives
idle_session_timeout and keeps its options.  In 010_pg_basebackup.pl,
check that a failed backup does not leave a --create-slot slot behind.
---
 doc/src/sgml/ref/pg_basebackup.sgml           |  20 ++
 src/bin/pg_basebackup/Makefile                |   4 +-
 src/bin/pg_basebackup/meson.build             |   2 +
 src/bin/pg_basebackup/pg_basebackup.c         | 220 ++++++++++++---
 src/bin/pg_basebackup/streamutil.c            |  25 +-
 src/bin/pg_basebackup/streamutil.h            |   1 +
 src/bin/pg_basebackup/t/010_pg_basebackup.pl  |  19 ++
 .../pg_basebackup/t/013_wal_slot_timing.pl    | 263 ++++++++++++++++++
 8 files changed, 517 insertions(+), 37 deletions(-)
 create mode 100644 src/bin/pg_basebackup/t/013_wal_slot_timing.pl

diff --git a/doc/src/sgml/ref/pg_basebackup.sgml b/doc/src/sgml/ref/pg_basebackup.sgml
index b4a0faccf41..e9b38db0c2f 100644
--- a/doc/src/sgml/ref/pg_basebackup.sgml
+++ b/doc/src/sgml/ref/pg_basebackup.sgml
@@ -398,6 +398,26 @@ PostgreSQL documentation
             with the write-ahead log data, using this method requires no
             extra write-ahead logs to be saved on the source server.
            </para>
+           <para>
+            Unless <option>--no-slot</option> is given, or
+            <option>--slot</option> names an existing slot,
+            <application>pg_basebackup</application> creates a temporary
+            replication slot before the backup starts, to keep the
+            write-ahead log the backup needs.  A slot requested with
+            <option>--create-slot</option> is created later, when streaming
+            starts, and replaces the temporary slot.
+           </para>
+           <para>
+            The connection holding the temporary slot is idle until the
+            checkpoint at the start of the backup has completed, so
+            <xref linkend="guc-idle-session-timeout"/> is disabled on it.
+            If that checkpoint finds the slot past
+            <xref linkend="guc-max-slot-wal-keep-size"/> or
+            <xref linkend="guc-idle-replication-slot-timeout"/>, the server
+            closes the connection, which drops the slot.  If the connection
+            is closed, <application>pg_basebackup</application> prints a
+            warning and reconnects.
+           </para>
            <para>
             When tar format is used, the write-ahead log files will be
             written to a separate file named <filename>pg_wal.tar</filename>
diff --git a/src/bin/pg_basebackup/Makefile b/src/bin/pg_basebackup/Makefile
index df94fc27d02..12ff32e329b 100644
--- a/src/bin/pg_basebackup/Makefile
+++ b/src/bin/pg_basebackup/Makefile
@@ -12,13 +12,15 @@
 PGFILEDESC = "pg_basebackup/pg_receivewal/pg_recvlogical - streaming WAL and backup receivers"
 PGAPPICON=win32
 
-EXTRA_INSTALL=contrib/test_decoding
+EXTRA_INSTALL=contrib/test_decoding \
+	src/test/modules/injection_points
 
 subdir = src/bin/pg_basebackup
 top_builddir = ../../..
 include $(top_builddir)/src/Makefile.global
 
 # make these available to TAP test scripts
+export enable_injection_points
 export LZ4
 export TAR
 # Note that GZIP cannot be used directly as this environment variable is
diff --git a/src/bin/pg_basebackup/meson.build b/src/bin/pg_basebackup/meson.build
index 2d3b22ff06e..43905ed9fc3 100644
--- a/src/bin/pg_basebackup/meson.build
+++ b/src/bin/pg_basebackup/meson.build
@@ -96,11 +96,13 @@ tests += {
     'env': {'GZIP_PROGRAM': gzip.found() ? gzip.full_path() : '',
             'TAR': tar.found() ? tar.full_path() : '',
             'LZ4': program_lz4.found() ? program_lz4.full_path() : '',
+            'enable_injection_points': get_option('injection_points') ? 'yes' : 'no',
     },
     'tests': [
       't/010_pg_basebackup.pl',
       't/011_in_place_tablespace.pl',
       't/012_incremental_progress.pl',
+      't/013_wal_slot_timing.pl',
       't/020_pg_receivewal.pl',
       't/030_pg_recvlogical.pl',
       't/040_pg_createsubscriber.pl',
diff --git a/src/bin/pg_basebackup/pg_basebackup.c b/src/bin/pg_basebackup/pg_basebackup.c
index 4daf985ab83..658838d4799 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -108,6 +108,11 @@ typedef void (*WriteDataCallback) (size_t nbytes, char *buf,
  */
 #define MINIMUM_VERSION_FOR_WAL_SUMMARIES 170000
 
+/*
+ * idle_session_timeout was added in version 14.
+ */
+#define MINIMUM_VERSION_FOR_IDLE_SESSION_TIMEOUT 140000
+
 /*
  * Different ways to include WAL
  */
@@ -165,6 +170,15 @@ static bool found_existing_xlogdir = false;
 static bool made_tablespace_dirs = false;
 static bool found_tablespace_dirs = false;
 
+/* Connection for the background WAL receiver, see PrepareLogStreamer() */
+static PGconn *bgconn = NULL;
+
+/*
+ * Temporary slot reserving WAL until streaming starts, or NULL.  Without
+ * --slot it is also the slot we stream with.
+ */
+static char *temp_slot_name = NULL;
+
 /* Progress indicators */
 static uint64 totalsize_kb;
 static uint64 totaldone;
@@ -607,6 +621,169 @@ LogStreamerMain(logstreamer_param *param)
 	return 0;
 }
 
+/*
+ * Open a connection for the background WAL receiver.
+ *
+ * With a temporary slot, the connection is opened before BASE_BACKUP and
+ * stays idle until the backup's checkpoint has completed, which with a spread
+ * checkpoint can take minutes.  Disable idle_session_timeout on it, so that
+ * it is not closed while it waits, dropping its temporary slot.  Any options
+ * the main connection was opened with are kept, with ours added last so that
+ * they take precedence.
+ */
+static PGconn *
+GetStreamingConnection(void)
+{
+	char	   *options_val = NULL;
+	PGconn	   *tmpconn;
+
+	if (PQserverVersion(conn) >= MINIMUM_VERSION_FOR_IDLE_SESSION_TIMEOUT)
+	{
+		PQconninfoOption *opts;
+		char	   *option = NULL;
+
+		/*
+		 * Take the options from the main connection rather than from the
+		 * connection string, so that those given in PGOPTIONS are kept too.
+		 */
+		opts = PQconninfo(conn);
+		if (opts == NULL)
+			pg_fatal("out of memory");
+
+		for (PQconninfoOption *opt = opts; opt->keyword != NULL; ++opt)
+		{
+			if (strcmp(opt->keyword, "options") == 0 && opt->val &&
+				*opt->val)
+				option = opt->val;
+		}
+
+		options_val = psprintf("%s -c idle_session_timeout=0",
+							   (option == NULL) ? "" : option);
+
+		PQconninfoFree(opts);
+	}
+
+	tmpconn = GetConnectionWithOptions(options_val);
+	pg_free(options_val);
+
+	return tmpconn;
+}
+
+/*
+ * Open the connection for the background WAL receiver, and create a
+ * temporary slot on it that reserves WAL until streaming starts, also with
+ * --create-slot.  This must be done before BASE_BACKUP, as a checkpoint could
+ * otherwise remove WAL from the backup's start position before the receiver
+ * gets to it.
+ *
+ * Without a temporary slot, that is with --no-slot or with --slot naming an
+ * existing slot, there is nothing to reserve, so the connection is opened
+ * only after BASE_BACKUP has returned, in SetupStreamingSlot(), and is not
+ * left idle during the backup's checkpoint.
+ */
+static void
+PrepareLogStreamer(void)
+{
+	/* Temporary replication slots are only supported in 10 and newer */
+	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_TEMP_SLOTS)
+	{
+		temp_replication_slot = false;
+		return;
+	}
+
+	if (!temp_replication_slot && !create_slot)
+		return;
+
+	/* Get a WAL serving connection */
+	bgconn = GetStreamingConnection();
+	if (!bgconn)
+		/* Error message already written in GetConnection() */
+		exit(1);
+
+	temp_slot_name = psprintf("pg_basebackup_%u",
+							  (unsigned int) PQbackendPID(bgconn));
+	if (!CreateReplicationSlot(bgconn, temp_slot_name, NULL, true, true, true,
+							   false, false, false))
+		exit(1);
+	if (verbose)
+		pg_log_info("created temporary replication slot \"%s\"",
+					temp_slot_name);
+
+	/* Without --slot, stream with the temporary slot */
+	if (temp_replication_slot)
+		replication_slot = temp_slot_name;
+}
+
+/*
+ * Set up the slot to stream with, after BASE_BACKUP has returned.
+ *
+ * If the temporary slot's connection was lost during the backup's checkpoint,
+ * the slot is gone too, so reconnect and create it again.  The checkpoint
+ * should keep the WAL from the backup's start position, so the new slot
+ * covers it.
+ *
+ * The permanent slot for --create-slot is created here, after the checkpoint,
+ * and only then is the temporary slot dropped.
+ */
+static void
+SetupStreamingSlot(void)
+{
+	if (bgconn == NULL)
+	{
+		Assert(temp_slot_name == NULL);
+
+		bgconn = GetStreamingConnection();
+		if (!bgconn)
+			/* Error message already written in GetConnection() */
+			exit(1);
+	}
+	else if (temp_slot_name)
+	{
+		PGresult   *res = PQexec(bgconn, "IDENTIFY_SYSTEM");
+
+		if (PQresultStatus(res) != PGRES_TUPLES_OK)
+		{
+			pg_log_warning("connection for streaming write-ahead log was lost during the base backup checkpoint, reconnecting");
+			pg_log_warning_detail("%s", PQerrorMessage(bgconn));
+
+			PQfinish(bgconn);
+			bgconn = GetStreamingConnection();
+			if (!bgconn)
+				/* Error message already written in GetConnection() */
+				exit(1);
+
+			/* Recreate the temporary slot only if we stream with it */
+			if (temp_replication_slot)
+			{
+				if (!CreateReplicationSlot(bgconn, temp_slot_name, NULL, true,
+										   true, true, false, false, false))
+					exit(1);
+				if (verbose)
+					pg_log_info("created temporary replication slot \"%s\"",
+								temp_slot_name);
+			}
+			else
+				temp_slot_name = NULL;
+		}
+		PQclear(res);
+	}
+
+	if (create_slot)
+	{
+		if (!CreateReplicationSlot(bgconn, replication_slot, NULL, false, true,
+								   true, false, false, false))
+			exit(1);
+		if (verbose)
+			pg_log_info("created replication slot \"%s\"", replication_slot);
+
+		/*
+		 * The regular slot takes over.
+		 */
+		if (temp_slot_name && !DropReplicationSlot(bgconn, temp_slot_name))
+			exit(1);
+	}
+}
+
 /*
  * Initiate background process for receiving xlog during the backup.
  * The background stream will use its own database connection so we can
@@ -620,7 +797,10 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier,
 	logstreamer_param *param;
 	char		statusdir[MAXPGPATH];
 
+	Assert(bgconn != NULL);
+
 	param = pg_malloc0_object(logstreamer_param);
+	param->bgconn = bgconn;
 	param->timeline = timeline;
 	param->sysidentifier = sysidentifier;
 	param->wal_compress_algorithm = wal_compress_algorithm;
@@ -639,46 +819,12 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier,
 		pg_fatal("could not create pipe for background process: %m");
 #endif
 
-	/* Get a second connection */
-	param->bgconn = GetConnection();
-	if (!param->bgconn)
-		/* Error message already written in GetConnection() */
-		exit(1);
-
 	/* In post-10 cluster, pg_xlog has been renamed to pg_wal */
 	snprintf(param->xlog, sizeof(param->xlog), "%s/%s",
 			 basedir,
 			 PQserverVersion(conn) < MINIMUM_VERSION_FOR_PG_WAL ?
 			 "pg_xlog" : "pg_wal");
 
-	/* Temporary replication slots are only supported in 10 and newer */
-	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_TEMP_SLOTS)
-		temp_replication_slot = false;
-
-	/*
-	 * Create replication slot if requested
-	 */
-	if (temp_replication_slot && !replication_slot)
-		replication_slot = psprintf("pg_basebackup_%u",
-									(unsigned int) PQbackendPID(param->bgconn));
-	if (temp_replication_slot || create_slot)
-	{
-		if (!CreateReplicationSlot(param->bgconn, replication_slot, NULL,
-								   temp_replication_slot, true, true, false,
-								   false, false))
-			exit(1);
-
-		if (verbose)
-		{
-			if (temp_replication_slot)
-				pg_log_info("created temporary replication slot \"%s\"",
-							replication_slot);
-			else
-				pg_log_info("created replication slot \"%s\"",
-							replication_slot);
-		}
-	}
-
 	if (format == 'p')
 	{
 		/*
@@ -1970,6 +2116,10 @@ BaseBackup(char *compression_algorithm, char *compression_detail,
 									  compression_detail);
 	}
 
+	/* If streaming WAL, reserve it before starting the backup */
+	if (includewal == STREAM_WAL)
+		PrepareLogStreamer();
+
 	if (verbose)
 		pg_log_info("initiating base backup, waiting for checkpoint to complete");
 
@@ -2087,6 +2237,8 @@ BaseBackup(char *compression_algorithm, char *compression_detail,
 		pg_compress_algorithm wal_compress_algorithm;
 		int			wal_compress_level;
 
+		SetupStreamingSlot();
+
 		if (verbose)
 			pg_log_info("starting background WAL receiver");
 
diff --git a/src/bin/pg_basebackup/streamutil.c b/src/bin/pg_basebackup/streamutil.c
index 8086fde84db..cdf3febafb6 100644
--- a/src/bin/pg_basebackup/streamutil.c
+++ b/src/bin/pg_basebackup/streamutil.c
@@ -59,10 +59,21 @@ PGconn	   *conn = NULL;
  */
 PGconn *
 GetConnection(void)
+{
+	return GetConnectionWithOptions(NULL);
+}
+
+/*
+ * Like GetConnection(), but if options is not NULL, use it as the "options"
+ * connection parameter, replacing any given in the connection string.  The
+ * caller must include any options that should be kept.
+ */
+PGconn *
+GetConnectionWithOptions(const char *options)
 {
 	PGconn	   *tmpconn;
-	int			argcount = 7;	/* dbname, replication, fallback_app_name,
-								 * host, user, port, password */
+	int			argcount = 8;	/* dbname, replication, fallback_app_name,
+								 * host, user, port, options, password */
 	int			i;
 	const char **keywords;
 	const char **values;
@@ -108,6 +119,10 @@ GetConnection(void)
 
 		for (conn_opt = conn_opts; conn_opt->keyword != NULL; conn_opt++)
 		{
+			/* Our own options are added below */
+			if (options && strcmp(conn_opt->keyword, "options") == 0)
+				continue;
+
 			if (conn_opt->val != NULL && conn_opt->val[0] != '\0')
 			{
 				keywords[i] = conn_opt->keyword;
@@ -150,6 +165,12 @@ GetConnection(void)
 		values[i] = dbport;
 		i++;
 	}
+	if (options)
+	{
+		keywords[i] = "options";
+		values[i] = options;
+		i++;
+	}
 
 	/* If -W was given, force prompt for password, but only the first time */
 	need_password = (dbgetpassword == 1 && !password);
diff --git a/src/bin/pg_basebackup/streamutil.h b/src/bin/pg_basebackup/streamutil.h
index 115703e9c6c..8827b3eb328 100644
--- a/src/bin/pg_basebackup/streamutil.h
+++ b/src/bin/pg_basebackup/streamutil.h
@@ -30,6 +30,7 @@ extern int	WalSegSz;
 extern PGconn *conn;
 
 extern PGconn *GetConnection(void);
+extern PGconn *GetConnectionWithOptions(const char *options);
 
 /* Replication commands */
 extern bool CreateReplicationSlot(PGconn *conn, const char *slot_name,
diff --git a/src/bin/pg_basebackup/t/010_pg_basebackup.pl b/src/bin/pg_basebackup/t/010_pg_basebackup.pl
index 23a757b1c86..3840cd5296a 100644
--- a/src/bin/pg_basebackup/t/010_pg_basebackup.pl
+++ b/src/bin/pg_basebackup/t/010_pg_basebackup.pl
@@ -830,6 +830,25 @@ $node->command_fails_like(
 	'pg_basebackup fails with --create-slot --slot and a previously existing slot'
 );
 
+# A failure of BASE_BACKUP must not leave a slot created by --create-slot
+# behind.
+$node->command_fails_like(
+	[
+		@pg_basebackup_defs,
+		'--pgdata' => "$tempdir/backupxs_slot2",
+		'--create-slot',
+		'--slot' => 'slot2',
+		'--manifest-checksums' => 'bogus'
+	],
+	qr/unrecognized checksum algorithm/,
+	'pg_basebackup --create-slot fails when BASE_BACKUP fails');
+is( $node->safe_psql(
+		'postgres',
+		q{SELECT count(*) FROM pg_replication_slots WHERE slot_name = 'slot2'}
+	),
+	'0',
+	'no slot is left behind when pg_basebackup --create-slot fails');
+
 $node->safe_psql('postgres',
 	q{SELECT * FROM pg_create_physical_replication_slot('slot1')});
 my $lsn = $node->safe_psql('postgres',
diff --git a/src/bin/pg_basebackup/t/013_wal_slot_timing.pl b/src/bin/pg_basebackup/t/013_wal_slot_timing.pl
new file mode 100644
index 00000000000..eb4c90f3ad7
--- /dev/null
+++ b/src/bin/pg_basebackup/t/013_wal_slot_timing.pl
@@ -0,0 +1,263 @@
+# Copyright (c) 2026, PostgreSQL Global Development Group
+
+# Check that pg_basebackup's replication slot reserves WAL from before the
+# backup's start position.  If the slot were created only after BASE_BACKUP
+# had returned the start position, a checkpoint running in between could
+# remove the WAL the backup needs, and streaming it would fail.
+#
+# We hold the slot creation with an injection point, force WAL past several
+# segments and checkpoint, then let the slot creation continue.
+#
+# Also check when the WAL streaming connection is opened, that it is kept
+# open while it waits for the backup's checkpoint, and that pg_basebackup
+# reconnects if that checkpoint terminates the connection holding the
+# temporary slot.
+
+use strict;
+use warnings FATAL => 'all';
+use PostgreSQL::Test::Cluster;
+use PostgreSQL::Test::Utils;
+use Test::More;
+
+if ($ENV{enable_injection_points} ne 'yes')
+{
+	plan skip_all => 'Injection points not supported by this build';
+}
+
+my $tempdir = PostgreSQL::Test::Utils::tempdir;
+
+my $node = PostgreSQL::Test::Cluster->new('main');
+$node->init(allows_streaming => 1);
+$node->append_conf(
+	'postgresql.conf', q{
+wal_keep_size = 0
+checkpoint_timeout = 1h
+});
+$node->start;
+
+if (!$node->check_extension('injection_points'))
+{
+	plan skip_all => 'Extension injection_points not installed';
+}
+
+$node->safe_psql('postgres', 'CREATE EXTENSION injection_points');
+$node->safe_psql('postgres',
+	"SELECT injection_points_attach('replication-slot-create-begin', 'wait')"
+);
+
+my $backupdir = "$tempdir/backup";
+my ($stdout, $stderr);
+my $h = IPC::Run::start(
+	[
+		'pg_basebackup', '--no-sync',
+		'--checkpoint' => 'fast',
+		'--pgdata' => $backupdir,
+		'--wal-method' => 'stream',
+		'--dbname' => $node->connstr('postgres'),
+	],
+	'>' => \$stdout,
+	'2>' => \$stderr);
+
+# Wait until the walsender is about to create pg_basebackup's slot.
+$node->wait_for_event('walsender', 'replication-slot-create-begin');
+
+# Move WAL forward by several segments and checkpoint, so that every segment
+# not protected by a slot or wal_keep_size is removed or recycled.
+$node->advance_wal(3);
+$node->safe_psql('postgres', 'CHECKPOINT');
+
+$node->safe_psql('postgres',
+	"SELECT injection_points_detach('replication-slot-create-begin')");
+$node->safe_psql('postgres',
+	"SELECT injection_points_wakeup('replication-slot-create-begin')");
+
+my $ok = $h->finish;
+ok($ok, 'pg_basebackup succeeds with WAL activity during slot creation')
+  or diag("pg_basebackup stderr:\n$stderr");
+unlike(
+	$stderr,
+	qr/has already been removed/,
+	'no WAL needed by the backup was removed');
+
+# pg_verifybackup also parses the WAL the backup needs, so this fails if
+# any of it is missing.
+$node->command_ok([ 'pg_verifybackup', $backupdir ],
+	'backup with streamed WAL verifies');
+
+# With a temporary slot, the WAL streaming connection is opened before
+# BASE_BACKUP and is idle until the backup's checkpoint has completed.
+# pg_basebackup disables idle_session_timeout on it, so it must not be closed
+# while it waits, even if the checkpoint takes longer than the timeout.  Hold
+# the checkpoint until the connection has been idle for several times the
+# timeout.  If it were closed, this would wait until the test times out.
+#
+# The options given in the connection string must still be used on that
+# connection.  log_replication_commands is enabled only through them, so the
+# temporary slot's creation is logged only if they were kept.
+#
+# Without a temporary slot, with --no-slot or with --slot naming an existing
+# slot, the connection must be opened only after BASE_BACKUP has returned, so
+# while the checkpoint is held, the only walsender is the one running
+# BASE_BACKUP.
+$node->append_conf(
+	'postgresql.conf', q{
+idle_session_timeout = '1s'
+log_replication_commands = off
+});
+$node->reload;
+$node->safe_psql('postgres',
+	"SELECT pg_create_physical_replication_slot('existing_slot', true)");
+
+my $connstr_with_options =
+  $node->connstr('postgres') . " options='-c log_replication_commands=on'";
+
+foreach my $case (
+	[ 'temporary slot', 'backup_session_temp', 1, [] ],
+	[ '--no-slot', 'backup_session_noslot', 0, ['--no-slot'] ],
+	[
+		'--slot', 'backup_session_existing',
+		0, [ '--slot' => 'existing_slot' ]
+	])
+{
+	my ($desc, $dirname, $early, $slot_opts) = @$case;
+	my $dir = "$tempdir/$dirname";
+
+	$node->safe_psql('postgres',
+		"SELECT injection_points_attach('checkpoint-before-old-wal-removal', 'wait')"
+	);
+
+	my $log_offset = -s $node->logfile;
+	my ($s_stdout, $s_stderr);
+	my $s_h = IPC::Run::start(
+		[
+			'pg_basebackup', '--no-sync',
+			'--checkpoint' => 'fast',
+			'--pgdata' => $dir,
+			'--wal-method' => 'stream',
+			@$slot_opts,
+			'--dbname' => $connstr_with_options,
+		],
+		'>' => \$s_stdout,
+		'2>' => \$s_stderr);
+
+	$node->wait_for_event('checkpointer',
+		'checkpoint-before-old-wal-removal');
+	if ($early)
+	{
+		$node->poll_query_until(
+			'postgres', q{
+			SELECT count(*) > 0 FROM pg_stat_activity
+			WHERE backend_type = 'walsender' AND state = 'idle'
+			  AND now() - state_change > interval '3s'})
+		  or die
+		  "timed out waiting for the WAL streaming connection to stay idle";
+	}
+	else
+	{
+		is( $node->safe_psql(
+				'postgres', q{
+				SELECT count(*) FROM pg_stat_activity
+				WHERE backend_type = 'walsender'}),
+			'1',
+			"no WAL streaming connection during the checkpoint with $desc");
+	}
+
+	$node->safe_psql('postgres',
+		"SELECT injection_points_detach('checkpoint-before-old-wal-removal')"
+	);
+	$node->safe_psql('postgres',
+		"SELECT injection_points_wakeup('checkpoint-before-old-wal-removal')"
+	);
+
+	ok($s_h->finish, "backup with $desc and idle_session_timeout")
+	  or diag("pg_basebackup stderr:\n$s_stderr");
+	unlike(
+		$s_stderr,
+		qr/connection for streaming write-ahead log was lost/,
+		"WAL streaming connection with $desc was not lost");
+
+	if ($early)
+	{
+		ok( $node->log_contains(
+				qr/received replication command: CREATE_REPLICATION_SLOT "pg_basebackup_\d+" TEMPORARY/,
+				$log_offset),
+			"connection options are used for the WAL streaming connection with $desc"
+		);
+	}
+
+	$node->command_ok([ 'pg_verifybackup', $dir ],
+		"backup with $desc and idle_session_timeout verifies");
+}
+
+$node->safe_psql('postgres',
+	"SELECT pg_drop_replication_slot('existing_slot')");
+$node->append_conf(
+	'postgresql.conf', q{
+idle_session_timeout = 0
+log_replication_commands = on
+});
+$node->reload;
+
+# The temporary slot is created before the backup's checkpoint, so it starts
+# at the previous one.  If more WAL than max_slot_wal_keep_size was written
+# since then, the backup's checkpoint terminates the connection holding the
+# slot, which drops it.  pg_basebackup must then reconnect and still get all
+# the WAL the backup needs.
+my $knode = PostgreSQL::Test::Cluster->new('keep');
+$knode->init(allows_streaming => 1, extra => ['--wal-segsize=1']);
+$knode->append_conf(
+	'postgresql.conf', q{
+wal_keep_size = 0
+max_slot_wal_keep_size = 2MB
+checkpoint_timeout = 1h
+});
+$knode->start;
+
+foreach my $case (
+	[ 'temporary slot', 'backup_keep_temp', [] ],
+	[
+		'--create-slot', 'backup_keep_created',
+		[ '--create-slot', '--slot' => 'keep_slot' ]
+	])
+{
+	my ($desc, $dirname, $slot_opts) = @$case;
+	my $dir = "$tempdir/$dirname";
+
+	$knode->safe_psql('postgres', 'CHECKPOINT');
+	$knode->advance_wal(5);
+
+	my $log_offset = -s $knode->logfile;
+	$knode->command_checks_all(
+		[
+			'pg_basebackup', '--no-sync',
+			'--checkpoint' => 'fast',
+			'--pgdata' => $dir,
+			'--wal-method' => 'stream',
+			@$slot_opts,
+			'--dbname' => $knode->connstr('postgres'),
+		],
+		0,
+		[],
+		[
+			qr/connection for streaming write-ahead log was lost during the base backup checkpoint, reconnecting/
+		],
+		"backup with $desc and max_slot_wal_keep_size");
+
+	ok( $knode->log_contains(
+			qr/terminating process \d+ to release replication slot "pg_basebackup_\d+"/,
+			$log_offset),
+		"temporary slot's connection was terminated in backup with $desc");
+
+	$knode->command_ok([ 'pg_verifybackup', $dir ],
+		"backup with $desc and max_slot_wal_keep_size verifies");
+}
+
+is( $knode->safe_psql(
+		'postgres',
+		q{SELECT restart_lsn IS NOT NULL AND invalidation_reason IS NULL
+			FROM pg_replication_slots WHERE slot_name = 'keep_slot'}),
+	't',
+	'slot created by --create-slot is valid after the backup');
+$knode->safe_psql('postgres', "SELECT pg_drop_replication_slot('keep_slot')");
+
+done_testing();
-- 
2.56.1

