From 4d9fc283b9704abc2816294103aa30d4b0267878 Mon Sep 17 00:00:00 2001
From: Jesper St John <jesper@stjohn.se>
Date: Mon, 19 Oct 2026 15:35:59 +0200
Subject: [PATCH v4] pg_basebackup: Create and start WAL streaming slot before
 starting 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 its slot before sending
BASE_BACKUP, so that the slot reserves all the WAL the backup needs.

Creating the slot early means it sits idle during the backup's
checkpoint, which can take minutes with --checkpoint=spread.  From
version 18, idle_replication_slot_timeout can invalidate an idle slot at
the end of a checkpoint, and the backup would then fail.  To prevent
that, also start the WAL receiver before BASE_BACKUP, so that the slot is
in use.  It streams from the slot's restart position, which is read with
READ_REPLICATION_SLOT (version 15 and later).  After BASE_BACKUP, check
that the stream does not start after the backup's start position or on
a later timeline.

Without a slot, on older servers, or if the slot has no restart
position, the receiver is started after BASE_BACKUP as before.

As a result, the backup can contain WAL from before its start position,
and a slot created with --create-slot is left behind if BASE_BACKUP
fails.  Document both.

Add a TAP test with two cases.  The first holds slot creation with an
injection point while WAL is advanced and a checkpoint is run.  The
second holds the backup's checkpoint before it invalidates slots, and
uses slot-timeout-inval to check that pg_basebackup's slot is in use by
then.  Also add tests in 010_pg_basebackup.pl for the slots left after
BASE_BACKUP fails.
---
 doc/src/sgml/ref/pg_basebackup.sgml           |  18 +-
 src/bin/pg_basebackup/Makefile                |   4 +-
 src/bin/pg_basebackup/meson.build             |   2 +
 src/bin/pg_basebackup/pg_basebackup.c         | 219 +++++++++++++-----
 src/bin/pg_basebackup/t/010_pg_basebackup.pl  |  44 ++++
 .../pg_basebackup/t/013_wal_slot_timing.pl    | 147 ++++++++++++
 6 files changed, 373 insertions(+), 61 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..6385190a10c 100644
--- a/doc/src/sgml/ref/pg_basebackup.sgml
+++ b/doc/src/sgml/ref/pg_basebackup.sgml
@@ -398,6 +398,21 @@ 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>
+            When a replication slot is used for streaming and the server is
+            version 15 or later, streaming begins at the slot's restart
+            position before the backup is started, rather than at the
+            backup's start position, so the backup can contain write-ahead
+            log from before its start position.  For a slot created by
+            <application>pg_basebackup</application> (a temporary slot, or one
+            requested with <option>--create-slot</option>), the restart
+            position is the server's most recent checkpoint, or on a standby
+            its most recent restartpoint, at the time the slot is created.
+            For an existing slot given with <option>--slot</option>, it is
+            the slot's current restart position, which can be considerably
+            older.  With older servers, or with <option>--no-slot</option>,
+            streaming begins at the backup's start position.
+           </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>
@@ -514,7 +529,8 @@ PostgreSQL documentation
        <para>
         Specifies that the replication slot named by the
         <literal>--slot</literal> option should be created before starting
-        the backup.  An error is raised if the slot already exists.
+        the backup.  An error is raised if the slot already exists.  The slot
+        is not dropped if the backup subsequently fails.
        </para>
       </listitem>
      </varlistentry>
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 c3b87a19e76..57218cf962a 100644
--- a/src/bin/pg_basebackup/pg_basebackup.c
+++ b/src/bin/pg_basebackup/pg_basebackup.c
@@ -103,6 +103,11 @@ typedef void (*WriteDataCallback) (size_t nbytes, char *buf,
  */
 #define MINIMUM_VERSION_FOR_TERMINATED_TARFILE 150000
 
+/*
+ * READ_REPLICATION_SLOT supported from version 15
+ */
+#define MINIMUM_VERSION_FOR_READ_REPLICATION_SLOT 150000
+
 /*
  * pg_wal/summaries exists beginning with version 17.
  */
@@ -165,6 +170,12 @@ 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;
+
+/* Has the background WAL receiver been started? */
+static bool log_streamer_started = false;
+
 /* Progress indicators */
 static uint64 totalsize_kb;
 static uint64 totaldone;
@@ -608,49 +619,31 @@ LogStreamerMain(logstreamer_param *param)
 }
 
 /*
- * Initiate background process for receiving xlog during the backup.
- * The background stream will use its own database connection so we can
- * stream the logfile in parallel with the backups.
+ * Open the connection for the background WAL receiver and create its
+ * replication slot, if one is needed.
+ *
+ * This is done before BASE_BACKUP, so that the slot reserves all the WAL the
+ * backup needs before the backup's checkpoint removes any of it.
+ *
+ * The slot must then not sit idle during that checkpoint, which can be long
+ * with --checkpoint=spread, or idle_replication_slot_timeout (version 18+)
+ * may invalidate it.  So if the slot's restart position can be read
+ * (version 15 and later), return true with it in *startptr and *starttli,
+ * and the caller starts the receiver there right away.  Otherwise return
+ * false, and the receiver is started after BASE_BACKUP.
  */
-static void
-StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier,
-				 pg_compress_algorithm wal_compress_algorithm,
-				 int wal_compress_level)
+static bool
+PrepareLogStreamer(XLogRecPtr *startptr, TimeLineID *starttli)
 {
-	logstreamer_param *param;
-	char		statusdir[MAXPGPATH];
+	XLogRecPtr	restart_lsn;
+	TimeLineID	restart_tli;
 
-	param = pg_malloc0_object(logstreamer_param);
-	param->timeline = timeline;
-	param->sysidentifier = sysidentifier;
-	param->wal_compress_algorithm = wal_compress_algorithm;
-	param->wal_compress_level = wal_compress_level;
-
-	/* Convert the starting position */
-	if (!pg_parse_lsn(startpos, &param->startptr))
-		pg_fatal("could not parse write-ahead log location \"%s\"",
-				 startpos);
-	/* Round off to even segment position */
-	param->startptr -= XLogSegmentOffset(param->startptr, WalSegSz);
-
-#ifndef WIN32
-	/* Create our background pipe */
-	if (pipe(bgpipe) < 0)
-		pg_fatal("could not create pipe for background process: %m");
-#endif
-
-	/* Get a second connection */
-	param->bgconn = GetConnection();
-	if (!param->bgconn)
+	/* Get a WAL serving connection */
+	bgconn = GetConnection();
+	if (!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;
@@ -660,10 +653,10 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier,
 	 */
 	if (temp_replication_slot && !replication_slot)
 		replication_slot = psprintf("pg_basebackup_%u",
-									(unsigned int) PQbackendPID(param->bgconn));
+									(unsigned int) PQbackendPID(bgconn));
 	if (temp_replication_slot || create_slot)
 	{
-		if (!CreateReplicationSlot(param->bgconn, replication_slot, NULL,
+		if (!CreateReplicationSlot(bgconn, replication_slot, NULL,
 								   temp_replication_slot, true, true, false,
 								   false, false))
 			exit(1);
@@ -679,6 +672,65 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier,
 		}
 	}
 
+	/* if --no-slot is used */
+	if (replication_slot == NULL)
+		return false;
+
+	/* GetSlotInformation doesn't exist pre version 15 */
+	if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_READ_REPLICATION_SLOT)
+		return false;
+
+	if (!GetSlotInformation(bgconn, replication_slot,
+							&restart_lsn, &restart_tli))
+		exit(1);
+
+	/* Check invalid xlog */
+	if (!XLogRecPtrIsValid(restart_lsn) || restart_tli == 0)
+		return false;
+
+	*startptr = restart_lsn;
+	*starttli = restart_tli;
+
+	return true;
+}
+
+/*
+ * Initiate background process for receiving xlog during the backup.
+ * The background stream will use its own database connection so we can
+ * stream the logfile in parallel with the backups.
+ */
+static void
+StartLogStreamer(XLogRecPtr startpos, uint32 timeline, char *sysidentifier,
+				 pg_compress_algorithm wal_compress_algorithm,
+				 int wal_compress_level)
+{
+	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;
+	param->wal_compress_level = wal_compress_level;
+
+	/* Round off to even segment */
+	param->startptr = startpos - XLogSegmentOffset(startpos, WalSegSz);
+
+#ifndef WIN32
+	/* Create our background pipe */
+	if (pipe(bgpipe) < 0)
+		pg_fatal("could not create pipe for background process: %m");
+#endif
+
+	/* 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");
+
 	if (format == 'p')
 	{
 		/*
@@ -734,6 +786,9 @@ StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier,
 	if (bgchild == 0)
 		pg_fatal("could not create background thread: %m");
 #endif
+
+	/* Mark streaming as started */
+	log_streamer_started = true;
 }
 
 /*
@@ -1747,6 +1802,11 @@ BaseBackup(char *compression_algorithm, char *compression_detail,
 	int			i;
 	char		xlogstart[64];
 	char		xlogend[64] = {0};
+	XLogRecPtr	xlogstartptr = InvalidXLogRecPtr;
+	XLogRecPtr	streamstartptr = InvalidXLogRecPtr;
+	TimeLineID	streamstarttli = 0;
+	pg_compress_algorithm wal_compress_algorithm = PG_COMPRESSION_NONE;
+	int			wal_compress_level = 0;
 	int			minServerMajor,
 				maxServerMajor;
 	int			serverVersion,
@@ -1970,6 +2030,37 @@ BaseBackup(char *compression_algorithm, char *compression_detail,
 									  compression_detail);
 	}
 
+	/*
+	 * If streaming WAL, create the replication slot before starting the
+	 * backup, so that it protects all the WAL the backup needs.  Start the
+	 * receiver right away if possible, so that the slot is in use, and so
+	 * cannot be invalidated as idle, while the server performs the
+	 * checkpoint.  See PrepareLogStreamer().
+	 */
+	if (includewal == STREAM_WAL)
+	{
+		if (client_compress->algorithm == PG_COMPRESSION_GZIP)
+		{
+			wal_compress_algorithm = PG_COMPRESSION_GZIP;
+			wal_compress_level = client_compress->level;
+		}
+		else
+		{
+			wal_compress_algorithm = PG_COMPRESSION_NONE;
+			wal_compress_level = 0;
+		}
+
+		if (PrepareLogStreamer(&streamstartptr, &streamstarttli))
+		{
+			if (verbose)
+				pg_log_info("starting background WAL receiver");
+
+			StartLogStreamer(streamstartptr, streamstarttli, sysidentifier,
+							 wal_compress_algorithm,
+							 wal_compress_level);
+		}
+	}
+
 	if (verbose)
 		pg_log_info("initiating base backup, waiting for checkpoint to complete");
 
@@ -2023,6 +2114,26 @@ BaseBackup(char *compression_algorithm, char *compression_detail,
 		pg_log_info("write-ahead log start point: %s on timeline %u",
 					xlogstart, starttli);
 
+	if (includewal == STREAM_WAL)
+	{
+		if (!pg_parse_lsn(xlogstart, &xlogstartptr))
+			pg_fatal("could not parse write-ahead log location \"%s\"",
+					 xlogstart);
+
+		/*
+		 * If the WAL receiver is running, make sure the stream start is older
+		 * than the basebackup start, in WAL and in timeline. An older stream
+		 * timeline is fine, the receiver should follow any timeline switches.
+		 */
+		if (log_streamer_started && xlogstartptr < streamstartptr)
+			pg_fatal("backup start point %s is older than the start of the WAL stream at %X/%08X",
+					 xlogstart, LSN_FORMAT_ARGS(streamstartptr));
+
+		if (log_streamer_started && streamstarttli > starttli)
+			pg_fatal("backup start timeline %u is older than the WAL stream's start timeline %u",
+					 starttli, streamstarttli);
+	}
+
 	/*
 	 * Get the header
 	 */
@@ -2078,31 +2189,21 @@ BaseBackup(char *compression_algorithm, char *compression_detail,
 				 PQntuples(res));
 
 	/*
-	 * If we're streaming WAL, start the streaming session before we start
-	 * receiving the actual data chunks.
+	 * If the receiver could not be started before BASE_BACKUP (no slot, a
+	 * server older than version 15, or a slot without a restart position),
+	 * start it now, at the backup's start position.
 	 */
 	if (includewal == STREAM_WAL)
 	{
-		pg_compress_algorithm wal_compress_algorithm;
-		int			wal_compress_level;
-
-		if (verbose)
-			pg_log_info("starting background WAL receiver");
-
-		if (client_compress->algorithm == PG_COMPRESSION_GZIP)
+		if (!log_streamer_started)
 		{
-			wal_compress_algorithm = PG_COMPRESSION_GZIP;
-			wal_compress_level = client_compress->level;
-		}
-		else
-		{
-			wal_compress_algorithm = PG_COMPRESSION_NONE;
-			wal_compress_level = 0;
-		}
+			if (verbose)
+				pg_log_info("starting background WAL receiver");
 
-		StartLogStreamer(xlogstart, starttli, sysidentifier,
-						 wal_compress_algorithm,
-						 wal_compress_level);
+			StartLogStreamer(xlogstartptr, starttli, sysidentifier,
+							 wal_compress_algorithm,
+							 wal_compress_level);
+		}
 	}
 
 	if (serverMajor >= 1500)
diff --git a/src/bin/pg_basebackup/t/010_pg_basebackup.pl b/src/bin/pg_basebackup/t/010_pg_basebackup.pl
index 23a757b1c86..367cc1da56f 100644
--- a/src/bin/pg_basebackup/t/010_pg_basebackup.pl
+++ b/src/bin/pg_basebackup/t/010_pg_basebackup.pl
@@ -829,9 +829,53 @@ $node->command_fails_like(
 	qr/replication slot "slot0" already exists/,
 	'pg_basebackup fails with --create-slot --slot and a previously existing slot'
 );
+is( $node->safe_psql(
+		'postgres',
+		q{SELECT slot_name FROM pg_replication_slots WHERE slot_name = 'slot0'}
+	),
+	'slot0',
+	'previously existing slot is not dropped when --create-slot fails');
+
+# The slot is created before BASE_BACKUP is sent, and is not dropped if
+# BASE_BACKUP itself fails.
+$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'}
+	),
+	'1',
+	'slot created by failed pg_basebackup --create-slot is kept');
+$node->safe_psql('postgres',
+	q{SELECT pg_drop_replication_slot('slot2')});
 
 $node->safe_psql('postgres',
 	q{SELECT * FROM pg_create_physical_replication_slot('slot1')});
+
+# Without --create-slot, a failed backup must leave the given slot alone.
+$node->command_fails_like(
+	[
+		@pg_basebackup_defs,
+		'--pgdata' => "$tempdir/backupxs_slot1_fail",
+		'--slot' => 'slot1',
+		'--manifest-checksums' => 'bogus'
+	],
+	qr/unrecognized checksum algorithm/,
+	'pg_basebackup --slot fails when BASE_BACKUP fails');
+is( $node->safe_psql(
+		'postgres',
+		q{SELECT slot_name FROM pg_replication_slots WHERE slot_name = 'slot1'}
+	),
+	'slot1',
+	'existing slot is not dropped when pg_basebackup --slot fails');
 my $lsn = $node->safe_psql('postgres',
 	q{SELECT restart_lsn FROM pg_replication_slots WHERE slot_name = 'slot1'}
 );
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..01bb37eb880
--- /dev/null
+++ b/src/bin/pg_basebackup/t/013_wal_slot_timing.pl
@@ -0,0 +1,147 @@
+# 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 that the slot, created before BASE_BACKUP, is already in use
+# when the backup's checkpoint runs, so that the checkpoint cannot
+# invalidate it under idle_replication_slot_timeout.
+
+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
+idle_replication_slot_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');
+
+# Now the idle timeout.  idle_replication_slot_timeout is set, and with
+# slot-timeout-inval attached, every checkpoint invalidates every slot that
+# is idle at that moment, however briefly.  Hold the backup's checkpoint just
+# before it checks the slots, wait until pg_basebackup's slot is being
+# streamed from, and then let the checkpoint continue.  An idle slot created
+# beforehand shows that the checkpoint does invalidate idle slots.
+$node->safe_psql('postgres',
+	"SELECT pg_create_physical_replication_slot('idle_slot', true)");
+$node->safe_psql('postgres',
+	"SELECT injection_points_attach('slot-timeout-inval', 'error')");
+$node->safe_psql('postgres',
+	"SELECT injection_points_attach('checkpoint-before-old-wal-removal', 'wait')"
+);
+
+my $backupdir2 = "$tempdir/backup_idle";
+$h = IPC::Run::start(
+	[
+		'pg_basebackup', '--no-sync',
+		'--checkpoint' => 'fast',
+		'--pgdata' => $backupdir2,
+		'--wal-method' => 'stream',
+		'--dbname' => $node->connstr('postgres'),
+	],
+	'>' => \$stdout,
+	'2>' => \$stderr);
+
+$node->wait_for_event('checkpointer', 'checkpoint-before-old-wal-removal');
+
+# A slot that is being streamed from has no inactive_since.
+my $in_use = $node->poll_query_until(
+	'postgres', q{
+	SELECT count(*) = 1 FROM pg_replication_slots
+		WHERE slot_name LIKE 'pg\_basebackup\_%' AND inactive_since IS NULL
+});
+ok($in_use, "pg_basebackup's slot is in use during the backup's checkpoint");
+
+# Detach before waking up, so that later checkpoints, such as the one at
+# shutdown, do not wait.
+$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 = $h->finish;
+ok($ok, 'pg_basebackup succeeds when idle slots are invalidated')
+  or diag("pg_basebackup stderr:\n$stderr");
+
+is( $node->safe_psql(
+		'postgres',
+		q{SELECT invalidation_reason FROM pg_replication_slots
+			WHERE slot_name = 'idle_slot'}),
+	'idle_timeout',
+	'idle slot was invalidated by the backup\'s checkpoint');
+
+$node->safe_psql('postgres',
+	"SELECT injection_points_detach('slot-timeout-inval')");
+
+$node->command_ok([ 'pg_verifybackup', $backupdir2 ],
+	'backup taken while idle slots are invalidated verifies');
+
+done_testing();
-- 
2.56.1

