From d0f91d2e4ee1fd4a01c0381193320978768ecdfb Mon Sep 17 00:00:00 2001
From: Antonin Houska <ah@cybertec.at>
Date: Fri, 13 Nov 2026 13:55:38 +0100
Subject: [PATCH 1/2] Allow progress tracking of sub-commands.

Some commands that support progress reporting run other commands which also
need to report their progress. The typical case is that REPACK ("parent
command") runs index build (sub-command).

The current approach is to disable progress tracking when a command is running
as a sub-command of another command, however it's not implemented thoroughly.
Moreover, as the progress reporting can be AM-specific, it's not really
practicable to pass the information whether progress reporting should be
enabled to all the places where we need it.

Instead of disabling the progress tracking of the sub-command, this patch
saves the progress information of the parent command when the sub-command
starts its reporting, and restores it when the sub-command is done. Thus the
progress information of the sub-command does not get mixed up with that of the
parent command.

A backend-local stack is used to store the status of the current command
before monitoring of the sub-command is started, so it's fine if the
sub-command starts its own sub-command, etc. However, shared memory is needed
for each backend to make the progress information available to users, and it
would be rather tricky to change its size dynamically as the nesting level of
progress reporting commands grows. Alternatively, we could allocate a fixed
amount of shared memory that "should" always be enough, however that amount
would be allocated for each backend, even if the nesting level is 1 or 2 in
most cases.

The approach we take here is that only the progress of the innermost command
(i.e. the actually running one) and the topmost command (i.e. the one started
by the user and waiting for completion of its sucommand(s)) is visible via
system views. Even though the topmost command is not making any progress while
waiting for the subcommand(s), it might be confusing for the user if it
disappeared from the monitoring system views temporarily. On the other hand,
if the nesting level is 3 or more (which should be pretty rare), the user
should not really miss the (waiting) commands in the middle of the stack.
---
 src/backend/access/heap/vacuumlazy.c          |   4 +-
 src/backend/access/transam/xact.c             |   8 +-
 src/backend/backup/basebackup_progress.c      |   2 +-
 src/backend/bootstrap/bootstrap.c             |  11 +-
 src/backend/catalog/heap.c                    |  13 +-
 src/backend/catalog/index.c                   |  50 ++--
 src/backend/catalog/toasting.c                |  12 +-
 src/backend/commands/analyze.c                |   4 +-
 src/backend/commands/copyfrom.c               |   2 +-
 src/backend/commands/copyto.c                 |   2 +-
 src/backend/commands/indexcmds.c              |  64 ++---
 src/backend/commands/repack.c                 |  37 ++-
 src/backend/commands/vacuumparallel.c         |   2 +-
 src/backend/postmaster/datachecksum_state.c   |   4 +-
 src/backend/utils/activity/backend_progress.c | 218 ++++++++++++++++--
 src/backend/utils/activity/backend_status.c   |   8 +-
 src/backend/utils/adt/pgstatfuncs.c           |  18 +-
 src/include/catalog/index.h                   |  11 +-
 src/include/utils/backend_progress.h          |   6 +-
 src/include/utils/backend_status.h            |  49 +++-
 src/test/modules/injection_points/Makefile    |   1 +
 .../injection_points/expected/progress.out    |  68 ++++++
 src/test/modules/injection_points/meson.build |   1 +
 .../injection_points/specs/progress.spec      |  66 ++++++
 src/tools/pgindent/typedefs.list              |   2 +
 25 files changed, 539 insertions(+), 124 deletions(-)
 create mode 100644 src/test/modules/injection_points/expected/progress.out
 create mode 100644 src/test/modules/injection_points/specs/progress.spec

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 1393c57ad8f..38878c9954d 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -981,7 +981,7 @@ heap_vacuum_rel(Relation rel, const VacuumParams *params,
 						 vacrel->recently_dead_tuples +
 						 vacrel->missed_dead_tuples,
 						 starttime);
-	pgstat_progress_end_command();
+	pgstat_progress_end_command(false);
 
 	if (instrument)
 	{
@@ -1164,7 +1164,7 @@ heap_vacuum_rel(Relation rel, const VacuumParams *params,
 				 * the st_progress_param array.
 				 */
 				appendStringInfo(&buf, _("delay time: %.3f ms\n"),
-								 (double) MyBEEntry->st_progress_param[PROGRESS_VACUUM_DELAY_TIME] / 1000000.0);
+								 (double) MyBEEntry->st_progress.param[PROGRESS_VACUUM_DELAY_TIME] / 1000000.0);
 			}
 			if (track_io_timing)
 			{
diff --git a/src/backend/access/transam/xact.c b/src/backend/access/transam/xact.c
index d8d91bed427..fd3bf18f908 100644
--- a/src/backend/access/transam/xact.c
+++ b/src/backend/access/transam/xact.c
@@ -2261,6 +2261,7 @@ StartTransaction(void)
 	AtStart_GUC();
 	AtStart_Cache();
 	AfterTriggerBeginXact();
+	AtStart_BackendProgress(s->nestingLevel);
 
 	/*
 	 * done with start processing, set current transaction state to "in
@@ -2899,7 +2900,8 @@ AbortTransaction(void)
 
 	/* Clear wait information and command progress indicator */
 	pgstat_report_wait_end();
-	pgstat_progress_end_command();
+	AtEOXact_BackendProgress(s->nestingLevel);
+	pgstat_progress_end_command(true);
 
 	pgaio_error_cleanup();
 
@@ -5181,6 +5183,7 @@ StartSubTransaction(void)
 	AtSubStart_Memory();
 	AtSubStart_ResourceOwner();
 	AfterTriggerBeginSubXact();
+	AtSubStart_BackendProgress(s->nestingLevel);
 
 	s->state = TRANS_INPROGRESS;
 
@@ -5343,7 +5346,8 @@ AbortSubTransaction(void)
 	WaitLSNCleanup();
 
 	pgstat_report_wait_end();
-	pgstat_progress_end_command();
+	AtEOSubXact_BackendProgress(s->nestingLevel);
+	pgstat_progress_end_command(true);
 
 	pgaio_error_cleanup();
 
diff --git a/src/backend/backup/basebackup_progress.c b/src/backend/backup/basebackup_progress.c
index f74459181d0..ad1ad27231d 100644
--- a/src/backend/backup/basebackup_progress.c
+++ b/src/backend/backup/basebackup_progress.c
@@ -191,7 +191,7 @@ bbsink_progress_archive_contents(bbsink *sink, size_t len)
 static void
 bbsink_progress_cleanup(bbsink *sink)
 {
-	pgstat_progress_end_command();
+	pgstat_progress_end_command(false);
 	bbsink_forward_cleanup(sink);
 }
 
diff --git a/src/backend/bootstrap/bootstrap.c b/src/backend/bootstrap/bootstrap.c
index 00786d8c0fa..2f0407f7fdd 100644
--- a/src/backend/bootstrap/bootstrap.c
+++ b/src/backend/bootstrap/bootstrap.c
@@ -40,6 +40,7 @@
 #include "storage/ipc.h"
 #include "storage/proc.h"
 #include "storage/shmem_internal.h"
+#include "utils/backend_progress.h"
 #include "utils/builtins.h"
 #include "utils/fmgroids.h"
 #include "utils/guc.h"
@@ -1190,7 +1191,15 @@ build_indices(void)
 		heap = table_open(ILHead->il_heap, NoLock);
 		ind = index_open(ILHead->il_ind, NoLock);
 
-		index_build(heap, ind, ILHead->il_info, false, false, false);
+		/*
+		 * Progress tracking is not really needed here, but it's simpler to
+		 * start it than to disable it everywhere (including the specific
+		 * AMs).
+		 */
+		pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX,
+									  RelationGetRelid(heap));
+		index_build(heap, ind, ILHead->il_info, false, false);
+		pgstat_progress_end_command(false);
 
 		index_close(ind, NoLock);
 		table_close(heap, NoLock);
diff --git a/src/backend/catalog/heap.c b/src/backend/catalog/heap.c
index 49ef6652203..94bcd1d0a60 100644
--- a/src/backend/catalog/heap.c
+++ b/src/backend/catalog/heap.c
@@ -3896,10 +3896,15 @@ RelationTruncateIndexes(Relation heapRelation)
 		 */
 		RelationTruncate(currentIndex, 0);
 
-		/* Initialize the index and rebuild */
-		/* Note: we do not need to re-establish pkey setting */
-		index_build(heapRelation, currentIndex, indexInfo, true, false,
-					true);
+		/*
+		 * Initialize the index and rebuild
+		 *
+		 * Note: we do not need to re-establish pkey setting
+		 */
+		pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX,
+									  RelationGetRelid(heapRelation));
+		index_build(heapRelation, currentIndex, indexInfo, true, false);
+		pgstat_progress_end_command(false);
 
 		/* We're done with this index */
 		index_close(currentIndex, NoLock);
diff --git a/src/backend/catalog/index.c b/src/backend/catalog/index.c
index 99413556572..d9bc82249d4 100644
--- a/src/backend/catalog/index.c
+++ b/src/backend/catalog/index.c
@@ -715,8 +715,6 @@ UpdateIndexRelation(Oid indexoid,
  *			already exists.
  *		INDEX_CREATE_PARTITIONED:
  *			create a partitioned index (table must be partitioned)
- *		INDEX_CREATE_SUPPRESS_PROGRESS:
- *			don't report progress during the index build.
  *		INDEX_CREATE_DEFERRABLE:
  *			index supports a deferrable constraint, mark it as
  *			non-immediate (indimmediate = false).
@@ -769,7 +767,6 @@ index_create(Relation heapRelation,
 	bool		invalid = (flags & INDEX_CREATE_INVALID) != 0;
 	bool		concurrent = (flags & INDEX_CREATE_CONCURRENT) != 0;
 	bool		partitioned = (flags & INDEX_CREATE_PARTITIONED) != 0;
-	bool		progress = (flags & INDEX_CREATE_SUPPRESS_PROGRESS) == 0;
 	char		relkind;
 	TransactionId relfrozenxid;
 	MultiXactId relminmxid;
@@ -1287,8 +1284,7 @@ index_create(Relation heapRelation,
 	}
 	else
 	{
-		index_build(heapRelation, indexRelation, indexInfo, false, true,
-					progress);
+		index_build(heapRelation, indexRelation, indexInfo, false, true);
 	}
 
 	/*
@@ -1555,7 +1551,7 @@ index_concurrently_build(Oid heapRelationId,
 	indexInfo->ii_BrokenHotChain = false;
 
 	/* Now build the index */
-	index_build(heapRel, indexRelation, indexInfo, false, true, true);
+	index_build(heapRel, indexRelation, indexInfo, false, true);
 
 	/* Roll back any GUC changes executed by index functions */
 	AtEOXact_GUC(false, save_nestlevel);
@@ -2236,6 +2232,8 @@ index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
 	 */
 	if (concurrent)
 	{
+		bool		progress;
+
 		/*
 		 * We must commit our transaction in order to make the first pg_index
 		 * state update visible to other sessions.  If the DROP machinery has
@@ -2306,11 +2304,12 @@ index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
 		 * to acquire an exclusive lock on our table.  The lock code will
 		 * detect deadlock and error out properly.
 		 *
-		 * Note: we report progress through WaitForLockers() unconditionally
-		 * here, even though it will only be used when we're called by REINDEX
-		 * CONCURRENTLY and not when called by DROP INDEX CONCURRENTLY.
+		 * Note: we report progress through WaitForLockers() only when the
+		 * command is REINDEX CONCURRENTLY. There's no progress reporting for
+		 * DROP INDEX CONCURRENTLY.
 		 */
-		WaitForLockers(heaplocktag, AccessExclusiveLock, true);
+		progress = MyBEEntry->st_progress.command == PROGRESS_COMMAND_CREATE_INDEX;
+		WaitForLockers(heaplocktag, AccessExclusiveLock, progress);
 
 		/*
 		 * Updating pg_index might involve TOAST table access, so ensure we
@@ -2334,7 +2333,7 @@ index_drop(Oid indexId, bool concurrent, bool concurrent_lock_mode)
 		 * Wait till every transaction that saw the old index state has
 		 * finished.  See above about progress reporting.
 		 */
-		WaitForLockers(heaplocktag, AccessExclusiveLock, true);
+		WaitForLockers(heaplocktag, AccessExclusiveLock, progress);
 
 		/*
 		 * Re-open relations to allow us to complete our actions.
@@ -3113,7 +3112,6 @@ index_update_stats(Relation rel,
  *
  * isreindex indicates we are recreating a previously-existing index.
  * parallel indicates if parallelism may be useful.
- * progress indicates if the backend should update its progress info.
  *
  * Note: before Postgres 8.2, the passed-in heap and index Relations
  * were automatically closed by this routine.  This is no longer the case.
@@ -3124,8 +3122,7 @@ index_build(Relation heapRelation,
 			Relation indexRelation,
 			IndexInfo *indexInfo,
 			bool isreindex,
-			bool parallel,
-			bool progress)
+			bool parallel)
 {
 	IndexBuildResult *stats;
 	Oid			save_userid;
@@ -3176,7 +3173,6 @@ index_build(Relation heapRelation,
 	RestrictSearchPath();
 
 	/* Set up initial progress report status */
-	if (progress)
 	{
 		const int	progress_index[] = {
 			PROGRESS_CREATEIDX_PHASE,
@@ -3742,7 +3738,6 @@ reindex_index(const ReindexStmt *stmt, Oid indexId,
 	IndexInfo  *indexInfo;
 	bool		skipped_constraint = false;
 	PGRUsage	ru0;
-	bool		progress = ((params->options & REINDEXOPT_REPORT_PROGRESS) != 0);
 	bool		set_tablespace = false;
 
 	pg_rusage_init(&ru0);
@@ -3777,7 +3772,6 @@ reindex_index(const ReindexStmt *stmt, Oid indexId,
 	save_nestlevel = NewGUCNestLevel();
 	RestrictSearchPath();
 
-	if (progress)
 	{
 		const int	progress_cols[] = {
 			PROGRESS_CREATEIDX_COMMAND,
@@ -3816,9 +3810,8 @@ reindex_index(const ReindexStmt *stmt, Oid indexId,
 		return;
 	}
 
-	if (progress)
-		pgstat_progress_update_param(PROGRESS_CREATEIDX_ACCESS_METHOD_OID,
-									 iRel->rd_rel->relam);
+	pgstat_progress_update_param(PROGRESS_CREATEIDX_ACCESS_METHOD_OID,
+								 iRel->rd_rel->relam);
 
 	/*
 	 * If a statement is available, telling that this comes from a REINDEX
@@ -3935,7 +3928,7 @@ reindex_index(const ReindexStmt *stmt, Oid indexId,
 
 	/* Initialize the index and rebuild */
 	/* Note: we do not need to re-establish pkey setting */
-	index_build(heapRelation, iRel, indexInfo, true, true, progress);
+	index_build(heapRelation, iRel, indexInfo, true, true);
 
 	/* Re-allow use of target index */
 	ResetReindexProcessing();
@@ -4029,8 +4022,7 @@ reindex_index(const ReindexStmt *stmt, Oid indexId,
 	index_close(iRel, NoLock);
 	table_close(heapRelation, NoLock);
 
-	if (progress)
-		pgstat_progress_end_command();
+	pgstat_progress_end_command(false);
 }
 
 /*
@@ -4202,9 +4194,15 @@ reindex_relation(const ReindexStmt *stmt, Oid relid, int flags,
 		/* Index should no longer be in the pending list */
 		Assert(!ReindexIsProcessingIndex(indexOid));
 
-		/* Set index rebuild count */
-		pgstat_progress_update_param(PROGRESS_REPACK_INDEX_REBUILD_COUNT,
-									 i);
+		/*
+		 * Set index rebuild count - only interesting for REPACK.
+		 *
+		 * XXX Shouldn't we add an argument indicating that the function is
+		 * being called from REPACK (or its subroutine)?
+		 */
+		if (MyBEEntry->st_progress.command == PROGRESS_COMMAND_REPACK)
+			pgstat_progress_update_param(PROGRESS_REPACK_INDEX_REBUILD_COUNT,
+										 i);
 		i++;
 	}
 
diff --git a/src/backend/catalog/toasting.c b/src/backend/catalog/toasting.c
index 3058ec14223..c0f2d951a04 100644
--- a/src/backend/catalog/toasting.c
+++ b/src/backend/catalog/toasting.c
@@ -30,6 +30,7 @@
 #include "catalog/toasting.h"
 #include "miscadmin.h"
 #include "nodes/makefuncs.h"
+#include "utils/backend_progress.h"
 #include "utils/fmgroids.h"
 #include "utils/rel.h"
 #include "utils/lsyscache.h"
@@ -381,9 +382,12 @@ create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
 	coloptions[1] = 0;
 
 	/*
-	 * Don't let index creation overwrite progress information for the command
-	 * that caused the TOAST table to be created.
+	 * XXX Progress reporting makes little sense for empty table, but
+	 * index_create() does report the progress and it's not worth disabling it
+	 * in this specific case.
 	 */
+	pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX,
+								  RelationGetRelid(toast_rel));
 	index_create(toast_rel, toast_idxname, toastIndexOid, InvalidOid,
 				 InvalidOid, InvalidOid,
 				 indexInfo,
@@ -391,8 +395,8 @@ create_toast_table(Relation rel, Oid toastOid, Oid toastIndexOid,
 				 BTREE_AM_OID,
 				 rel->rd_rel->reltablespace,
 				 collationIds, opclassIds, NULL, coloptions, NULL, (Datum) 0,
-				 INDEX_CREATE_IS_PRIMARY | INDEX_CREATE_SUPPRESS_PROGRESS,
-				 0, true, true, NULL);
+				 INDEX_CREATE_IS_PRIMARY, 0, true, true, NULL);
+	pgstat_progress_end_command(false);
 
 	table_close(toast_rel, NoLock);
 
diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c
index 6a405a6a6ff..31efe96536d 100644
--- a/src/backend/commands/analyze.c
+++ b/src/backend/commands/analyze.c
@@ -315,7 +315,7 @@ analyze_rel(Oid relid, RangeVar *relation,
 	relation_close(onerel, NoLock);
 
 out:
-	pgstat_progress_end_command();
+	pgstat_progress_end_command(false);
 }
 
 /*
@@ -848,7 +848,7 @@ do_analyze_rel(Relation onerel, const VacuumParams *params,
 				 * only updated by the calling process.
 				 */
 				appendStringInfo(&buf, _("delay time: %.3f ms\n"),
-								 (double) MyBEEntry->st_progress_param[PROGRESS_ANALYZE_DELAY_TIME] / 1000000.0);
+								 (double) MyBEEntry->st_progress.param[PROGRESS_ANALYZE_DELAY_TIME] / 1000000.0);
 			}
 			if (track_io_timing)
 			{
diff --git a/src/backend/commands/copyfrom.c b/src/backend/commands/copyfrom.c
index 89f48c8951b..665834561df 100644
--- a/src/backend/commands/copyfrom.c
+++ b/src/backend/commands/copyfrom.c
@@ -1958,7 +1958,7 @@ EndCopyFrom(CopyFromState cstate)
 							cstate->filename)));
 	}
 
-	pgstat_progress_end_command();
+	pgstat_progress_end_command(false);
 
 	MemoryContextDelete(cstate->copycontext);
 	pfree(cstate);
diff --git a/src/backend/commands/copyto.c b/src/backend/commands/copyto.c
index 9ca06ed3e18..eaac309f75a 100644
--- a/src/backend/commands/copyto.c
+++ b/src/backend/commands/copyto.c
@@ -776,7 +776,7 @@ EndCopy(CopyToState cstate)
 							cstate->filename)));
 	}
 
-	pgstat_progress_end_command();
+	pgstat_progress_end_command(false);
 
 	MemoryContextDelete(cstate->copycontext);
 
diff --git a/src/backend/commands/indexcmds.c b/src/backend/commands/indexcmds.c
index c8b88ba4f2a..00645b698fd 100644
--- a/src/backend/commands/indexcmds.c
+++ b/src/backend/commands/indexcmds.c
@@ -621,6 +621,7 @@ DefineIndex(ParseState *pstate,
 	Oid			root_save_userid;
 	int			root_save_sec_context;
 	int			root_save_nestlevel;
+	bool		progress_started = false;
 
 	root_save_nestlevel = NewGUCNestLevel();
 
@@ -649,16 +650,21 @@ DefineIndex(ParseState *pstate,
 		concurrent = false;
 
 	/*
-	 * Start progress report.  If we're building a partition, this was already
-	 * done.
+	 * Start progress report if not done yet.
+	 *
+	 * We could check parentIndexId and only start the reporting when
+	 * processing the parent index (i.e. parentIndexId is invalid), however
+	 * that wouldn't work when adding a partition to an existing table:
+	 * parentIndexId is always valid in that cases.
 	 */
-	if (!OidIsValid(parentIndexId))
+	if (MyBEEntry->st_progress.command == PROGRESS_COMMAND_INVALID)
 	{
 		pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, tableId);
 		pgstat_progress_update_param(PROGRESS_CREATEIDX_COMMAND,
 									 concurrent ?
 									 PROGRESS_CREATEIDX_COMMAND_CREATE_CONCURRENTLY :
 									 PROGRESS_CREATEIDX_COMMAND_CREATE);
+		progress_started = true;
 	}
 
 	/*
@@ -1320,9 +1326,8 @@ DefineIndex(ParseState *pstate,
 
 		table_close(rel, NoLock);
 
-		/* If this is the top-level index, we're done */
-		if (!OidIsValid(parentIndexId))
-			pgstat_progress_end_command();
+		if (progress_started)
+			pgstat_progress_end_command(false);
 
 		return address;
 	}
@@ -1614,21 +1619,18 @@ DefineIndex(ParseState *pstate,
 			}
 		}
 
-		/*
-		 * Indexes on partitioned tables are not themselves built, so we're
-		 * done here.
-		 */
 		AtEOXact_GUC(false, root_save_nestlevel);
 		SetUserIdAndSecContext(root_save_userid, root_save_sec_context);
 		table_close(rel, NoLock);
-		if (!OidIsValid(parentIndexId))
-			pgstat_progress_end_command();
-		else
+		if (OidIsValid(parentIndexId))
 		{
 			/* Update progress for an intermediate partitioned index itself */
 			pgstat_progress_incr_param(PROGRESS_CREATEIDX_PARTITIONS_DONE, 1);
 		}
 
+		if (progress_started)
+			pgstat_progress_end_command(false);
+
 		return address;
 	}
 
@@ -1641,14 +1643,14 @@ DefineIndex(ParseState *pstate,
 		table_close(rel, NoLock);
 
 		/*
-		 * If this is the top-level index, the command is done overall;
-		 * otherwise, increment progress to report one child index is done.
+		 * Increment progress to report one child index is done.
 		 */
-		if (!OidIsValid(parentIndexId))
-			pgstat_progress_end_command();
-		else
+		if (OidIsValid(parentIndexId))
 			pgstat_progress_incr_param(PROGRESS_CREATEIDX_PARTITIONS_DONE, 1);
 
+		if (progress_started)
+			pgstat_progress_end_command(false);
+
 		return address;
 	}
 
@@ -1862,7 +1864,8 @@ DefineIndex(ParseState *pstate,
 	 */
 	UnlockRelationIdForSession(&heaprelid, ShareUpdateExclusiveLock);
 
-	pgstat_progress_end_command();
+	if (progress_started)
+		pgstat_progress_end_command(false);
 
 	return address;
 }
@@ -3144,7 +3147,6 @@ ReindexIndex(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLev
 	{
 		ReindexParams newparams = *params;
 
-		newparams.options |= REINDEXOPT_REPORT_PROGRESS;
 		reindex_index(stmt, indOid, false, persistence, &newparams);
 	}
 }
@@ -3267,7 +3269,6 @@ ReindexTable(const ReindexStmt *stmt, const ReindexParams *params, bool isTopLev
 	{
 		ReindexParams newparams = *params;
 
-		newparams.options |= REINDEXOPT_REPORT_PROGRESS;
 		result = reindex_relation(stmt, heapOid,
 								  REINDEX_REL_PROCESS_TOAST |
 								  REINDEX_REL_CHECK_CONSTRAINTS,
@@ -3692,8 +3693,7 @@ ReindexMultipleInternal(const ReindexStmt *stmt, const List *relids, const Reind
 		{
 			ReindexParams newparams = *params;
 
-			newparams.options |=
-				REINDEXOPT_REPORT_PROGRESS | REINDEXOPT_MISSING_OK;
+			newparams.options |= REINDEXOPT_MISSING_OK;
 			reindex_index(stmt, relid, false, relpersistence, &newparams);
 			PopActiveSnapshot();
 			/* reindex_index() does the verbose output */
@@ -3703,8 +3703,7 @@ ReindexMultipleInternal(const ReindexStmt *stmt, const List *relids, const Reind
 			bool		result;
 			ReindexParams newparams = *params;
 
-			newparams.options |=
-				REINDEXOPT_REPORT_PROGRESS | REINDEXOPT_MISSING_OK;
+			newparams.options |= REINDEXOPT_MISSING_OK;
 			result = reindex_relation(stmt, relid,
 									  REINDEX_REL_PROCESS_TOAST |
 									  REINDEX_REL_CHECK_CONSTRAINTS,
@@ -4174,7 +4173,6 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 			elog(ERROR, "cannot reindex a temporary table concurrently");
 
 		pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, idx->tableId);
-
 		progress_vals[0] = PROGRESS_CREATEIDX_COMMAND_REINDEX_CONCURRENTLY;
 		progress_vals[1] = 0;	/* initializing */
 		progress_vals[2] = idx->indexId;
@@ -4198,11 +4196,11 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 		/* Create new index definition based on given index */
 		newIndexId = index_create_copy(heapRel,
 									   INDEX_CREATE_CONCURRENT |
-									   INDEX_CREATE_SKIP_BUILD |
-									   INDEX_CREATE_SUPPRESS_PROGRESS,
+									   INDEX_CREATE_SKIP_BUILD,
 									   idx->indexId,
 									   tablespaceid,
 									   concurrentName);
+		pgstat_progress_end_command(false);
 
 		/*
 		 * Now open the relation of the new index, a session-level lock is
@@ -4330,9 +4328,11 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 	 * DefineIndex() for more details.
 	 */
 
+	pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, relationOid);
 	pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
 								 PROGRESS_CREATEIDX_PHASE_WAIT_1);
 	WaitForLockersMultiple(lockTags, ShareLock, true);
+	pgstat_progress_end_command(false);
 	CommitTransactionCommand();
 
 	foreach(lc, newIndexIds)
@@ -4376,6 +4376,7 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 
 		/* Perform concurrent build of new index */
 		index_concurrently_build(newidx->tableId, newidx->indexId);
+		pgstat_progress_end_command(false);
 
 		ReindexUnpinRelations(pinnedRels);
 
@@ -4400,9 +4401,11 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 	 * for more details.
 	 */
 
+	pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, relationOid);
 	pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
 								 PROGRESS_CREATEIDX_PHASE_WAIT_2);
 	WaitForLockersMultiple(lockTags, ShareLock, true);
+	pgstat_progress_end_command(false);
 	CommitTransactionCommand();
 
 	foreach(lc, newIndexIds)
@@ -4482,6 +4485,7 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 		pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
 									 PROGRESS_CREATEIDX_PHASE_WAIT_3);
 		WaitForOlderSnapshots(limitXmin, true);
+		pgstat_progress_end_command(false);
 
 		CommitTransactionCommand();
 	}
@@ -4577,6 +4581,7 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 	 */
 
 	INJECTION_POINT("reindex-relation-concurrently-before-set-dead", NULL);
+	pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX, relationOid);
 	pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
 								 PROGRESS_CREATEIDX_PHASE_WAIT_4);
 	WaitForLockersMultiple(lockTags, AccessExclusiveLock, true);
@@ -4623,6 +4628,7 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 	pgstat_progress_update_param(PROGRESS_CREATEIDX_PHASE,
 								 PROGRESS_CREATEIDX_PHASE_WAIT_5);
 	WaitForLockersMultiple(lockTags, AccessExclusiveLock, true);
+	pgstat_progress_end_command(false);
 
 	PushActiveSnapshot(GetTransactionSnapshot());
 
@@ -4698,8 +4704,6 @@ ReindexRelationConcurrently(const ReindexStmt *stmt, Oid relationOid, const Rein
 
 	MemoryContextDelete(private_context);
 
-	pgstat_progress_end_command();
-
 	return true;
 }
 
diff --git a/src/backend/commands/repack.c b/src/backend/commands/repack.c
index eee8b646029..509bc76570c 100644
--- a/src/backend/commands/repack.c
+++ b/src/backend/commands/repack.c
@@ -712,7 +712,7 @@ out:
 	/* Restore userid and security context */
 	SetUserIdAndSecContext(save_userid, save_sec_context);
 
-	pgstat_progress_end_command();
+	pgstat_progress_end_command(false);
 }
 
 /*
@@ -2050,11 +2050,19 @@ finish_heap_swap(Oid OIDOldHeap, Oid OIDNewHeap,
 {
 	ObjectAddress object;
 	Oid			mapped_tables[4];
+	bool		is_repack;
 	int			i;
 
+	/*
+	 * XXX Shouldn't we add an argument indicating that the function is being
+	 * called from REPACK?
+	 */
+	is_repack = MyBEEntry->st_progress.command == PROGRESS_COMMAND_REPACK;
+
 	/* Report that we are now swapping relation files */
-	pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
-								 PROGRESS_REPACK_PHASE_SWAP_REL_FILES);
+	if (is_repack)
+		pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
+									 PROGRESS_REPACK_PHASE_SWAP_REL_FILES);
 
 	/* Zero out possible results from swapped_relation_files */
 	memset(mapped_tables, 0, sizeof(mapped_tables));
@@ -2111,15 +2119,17 @@ finish_heap_swap(Oid OIDOldHeap, Oid OIDNewHeap,
 			reindex_flags |= REINDEX_REL_FORCE_INDEXES_PERMANENT;
 
 		/* Report that we are now reindexing relations */
-		pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
-									 PROGRESS_REPACK_PHASE_REBUILD_INDEX);
+		if (is_repack)
+			pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
+										 PROGRESS_REPACK_PHASE_REBUILD_INDEX);
 
 		reindex_relation(NULL, OIDOldHeap, reindex_flags, &reindex_params);
 	}
 
 	/* Report that we are now doing clean up */
-	pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
-								 PROGRESS_REPACK_PHASE_FINAL_CLEANUP);
+	if (is_repack)
+		pgstat_progress_update_param(PROGRESS_REPACK_PHASE,
+									 PROGRESS_REPACK_PHASE_FINAL_CLEANUP);
 
 	/*
 	 * If the relation being rebuilt is pg_class, swap_relation_files()
@@ -3662,9 +3672,20 @@ build_new_indexes(Relation NewHeap, List *OldIndexes)
 									 "repacknew",
 									 get_rel_namespace(ind->rd_index->indrelid),
 									 false);
-		newindex = index_create_copy(NewHeap, INDEX_CREATE_SUPPRESS_PROGRESS,
+
+		/*
+		 * We build the index on the new heap, but after the swap phase it'll
+		 * become an index on the old heap. It makes more sense to report the
+		 * progress this way. (The reporting API expects that both command and
+		 * subcommand deal with the same target.)
+		 */
+		pgstat_progress_start_command(PROGRESS_COMMAND_CREATE_INDEX,
+									  RelationGetRelid(NewHeap));
+		newindex = index_create_copy(NewHeap, 0,
 									 oldindex, ind->rd_rel->reltablespace,
 									 newName);
+		pgstat_progress_end_command(false);
+
 		copy_index_constraints(ind, newindex, RelationGetRelid(NewHeap));
 		result = lappend_oid(result, newindex);
 
diff --git a/src/backend/commands/vacuumparallel.c b/src/backend/commands/vacuumparallel.c
index 339d876d6e2..b06375f3400 100644
--- a/src/backend/commands/vacuumparallel.c
+++ b/src/backend/commands/vacuumparallel.c
@@ -1406,7 +1406,7 @@ parallel_vacuum_main(dsm_segment *seg, shm_toc *toc)
 	/* Pop the error context stack */
 	error_context_stack = errcallback.previous;
 
-	pgstat_progress_end_command();
+	pgstat_progress_end_command(false);
 
 	vac_close_indexes(nindexes, indrels, RowExclusiveLock);
 	table_close(rel, ShareUpdateExclusiveLock);
diff --git a/src/backend/postmaster/datachecksum_state.c b/src/backend/postmaster/datachecksum_state.c
index e2b673a96b5..1c07d902e8e 100644
--- a/src/backend/postmaster/datachecksum_state.c
+++ b/src/backend/postmaster/datachecksum_state.c
@@ -1401,7 +1401,7 @@ done:
 	}
 
 	/* Shut down progress reporting as we are done */
-	pgstat_progress_end_command();
+	pgstat_progress_end_command(false);
 
 	launcher_running = false;
 	DataChecksumState->launcher_running = false;
@@ -1996,7 +1996,7 @@ DataChecksumsWorkerMain(Datum arg)
 	list_free(InitialTempTableList);
 
 	/* worker done */
-	pgstat_progress_end_command();
+	pgstat_progress_end_command(false);
 
 	LWLockAcquire(DataChecksumsWorkerLock, LW_EXCLUSIVE);
 	if (DataChecksumState->worker_invocation == worker_invocation)
diff --git a/src/backend/utils/activity/backend_progress.c b/src/backend/utils/activity/backend_progress.c
index 32b2cdd81cd..796ba15bebc 100644
--- a/src/backend/utils/activity/backend_progress.c
+++ b/src/backend/utils/activity/backend_progress.c
@@ -11,11 +11,54 @@
 #include "postgres.h"
 
 #include "access/parallel.h"
+#include "access/xact.h"
 #include "libpq/pqformat.h"
 #include "storage/proc.h"
 #include "utils/backend_progress.h"
 #include "utils/backend_status.h"
+#include "utils/injection_point.h"
+#include "utils/memutils.h"
 
+/*
+ * Set this variable to false when progress monitoring would not work. The
+ * obvious case is file_fdw, where a merge join can run two COPY commands at
+ * the same time - in such a case, the concept of parent commands does not
+ * help.
+ */
+bool		pgstat_track_progress = true;
+
+/*
+ * nestingLevel of the current transaction.
+ */
+static int xact_level = 0;
+
+/*
+ * Element of the parent command stack.
+ *
+ * XXX Is "outer" command more descriptive than "parent"?
+ */
+typedef struct PgBackendProgresElt
+{
+	PgBackendProgress progress;
+
+	struct PgBackendProgresElt *parent;
+} PgBackendProgresElt;
+
+/*
+ * Stack of outer commands.
+ *
+ * In the simple case, we only monitor the progress of a single command at a
+ * time. However, some monitored commands may launch other commands
+ * (sub-commands), which report their progress too. If we didn't care, the
+ * sub-command would override the output values of the parent command with
+ * values of its own, unrelated parameters.
+ *
+ * To avoid this, when the sub-command starts its monitoring, the progress of
+ * the parent command is pushed onto this stack and only the sub-command is
+ * monitored. Once the sub-command is done, monitoring of the parent command
+ * is resumed.
+ */
+static PgBackendProgresElt *parent_commands = NULL;
 
 /*-----------
  * pgstat_progress_start_command() -
@@ -28,16 +71,65 @@ void
 pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid)
 {
 	volatile PgBackendStatus *beentry = MyBEEntry;
+	MemoryContext oldcxt;
+	PgBackendProgresElt *parent_new = NULL;
+	bool	is_dummy = false;
 
-	if (!beentry || !pgstat_track_activities)
+	if (!beentry || !pgstat_track_activities || !pgstat_track_progress)
 		return;
 
+	/*
+	 * Allocate the new stack element regardless we need it, as we cannot do
+	 * that in a critical section below.
+	 */
+	oldcxt = MemoryContextSwitchTo(TopMemoryContext);
+	parent_new = palloc_object(PgBackendProgresElt);
+	MemoryContextSwitchTo(oldcxt);
+
 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
-	beentry->st_progress_command = cmdtype;
-	beentry->st_progress_command_target = relid;
+
+	/*
+	 * If progress monitoring is already in progress, save the status of the
+	 * parent command so that we can restore it later.
+	 */
+	if (beentry->st_progress.command != PROGRESS_COMMAND_INVALID)
+	{
+		parent_new->progress = beentry->st_progress;
+		parent_new->parent = parent_commands;
+		parent_commands = parent_new;
+
+		/* Do not free this element below. */
+		parent_new = NULL;
+
+		/* Report the top-level command if this is the first subcommand. */
+		if (beentry->st_progress_top.command == PROGRESS_COMMAND_INVALID)
+			beentry->st_progress_top = beentry->st_progress;
+	}
+
+	/*
+	 * Now check the stack to see if a command of the same type is already
+	 * being monitored.
+	 */
+	for (PgBackendProgresElt *stack_elt = parent_commands; stack_elt != NULL;
+		 stack_elt = stack_elt->parent)
+	{
+		if (stack_elt->progress.command == cmdtype)
+		{
+			/* Cannot really monitor the new command. */
+			is_dummy = true;
+			break;
+		}
+	}
+
+	beentry->st_progress.command = cmdtype;
+	beentry->st_progress.command_target = relid;
 	for (int i = 0; i < PGSTAT_NUM_PROGRESS_PARAM; i++)
-		beentry->st_progress_param[i] = 0;
+		beentry->st_progress.param[i] = 0;
+	beentry->st_progress.xact_level = xact_level;
+	beentry->st_progress.is_dummy = is_dummy;
 	PGSTAT_END_WRITE_ACTIVITY(beentry);
+	if (parent_new)
+		pfree(parent_new);
 }
 
 /*-----------
@@ -53,11 +145,16 @@ pgstat_progress_update_param(int index, int64 val)
 
 	Assert(index >= 0 && index < PGSTAT_NUM_PROGRESS_PARAM);
 
-	if (!beentry || !pgstat_track_activities)
+	if (!beentry || beentry->st_progress.is_dummy ||
+		!pgstat_track_activities || !pgstat_track_progress)
 		return;
 
+	/* Sub-commands introduce special cases that need to be tested. */
+	if (parent_commands)
+		INJECTION_POINT("progress-update-param-nested", NULL);
+
 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
-	beentry->st_progress_param[index] = val;
+	beentry->st_progress.param[index] = val;
 	PGSTAT_END_WRITE_ACTIVITY(beentry);
 }
 
@@ -74,11 +171,12 @@ pgstat_progress_incr_param(int index, int64 incr)
 
 	Assert(index >= 0 && index < PGSTAT_NUM_PROGRESS_PARAM);
 
-	if (!beentry || !pgstat_track_activities)
+	if (!beentry || beentry->st_progress.is_dummy ||
+		!pgstat_track_activities || !pgstat_track_progress)
 		return;
 
 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
-	beentry->st_progress_param[index] += incr;
+	beentry->st_progress.param[index] += incr;
 	PGSTAT_END_WRITE_ACTIVITY(beentry);
 }
 
@@ -124,7 +222,8 @@ pgstat_progress_update_multi_param(int nparam, const int *index,
 	volatile PgBackendStatus *beentry = MyBEEntry;
 	int			i;
 
-	if (!beentry || !pgstat_track_activities || nparam == 0)
+	if (!beentry || beentry->st_progress.is_dummy ||
+		!pgstat_track_activities || !pgstat_track_progress || nparam == 0)
 		return;
 
 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
@@ -133,7 +232,7 @@ pgstat_progress_update_multi_param(int nparam, const int *index,
 	{
 		Assert(index[i] >= 0 && index[i] < PGSTAT_NUM_PROGRESS_PARAM);
 
-		beentry->st_progress_param[index[i]] = val[i];
+		beentry->st_progress.param[index[i]] = val[i];
 	}
 
 	PGSTAT_END_WRITE_ACTIVITY(beentry);
@@ -144,21 +243,110 @@ pgstat_progress_update_multi_param(int nparam, const int *index,
  *
  * Reset st_progress_command (and st_progress_command_target) in own backend
  * entry.  This signals the end of the command.
+ *
+ * If 'xact' is true, end reporting for all the commands being reported by the
+ * current transaction.
  *-----------
  */
 void
-pgstat_progress_end_command(void)
+pgstat_progress_end_command(bool xact)
 {
 	volatile PgBackendStatus *beentry = MyBEEntry;
 
-	if (!beentry || !pgstat_track_activities)
+	if (!beentry || !pgstat_track_activities || !pgstat_track_progress)
 		return;
 
-	if (beentry->st_progress_command == PROGRESS_COMMAND_INVALID)
+	if (beentry->st_progress.command == PROGRESS_COMMAND_INVALID)
 		return;
 
+	/* Sub-commands introduce special cases that need to be tested. */
+	if (parent_commands)
+		INJECTION_POINT("progress-end-command-nested", NULL);
+
 	PGSTAT_BEGIN_WRITE_ACTIVITY(beentry);
-	beentry->st_progress_command = PROGRESS_COMMAND_INVALID;
-	beentry->st_progress_command_target = InvalidOid;
+	while (true)
+	{
+		if (parent_commands)
+		{
+			PgBackendProgresElt *parent;
+
+			/*
+			 * If dealing with transaction end, do not touch commands started
+			 * in parent transaction.
+			 */
+			if (xact && beentry->st_progress.xact_level < xact_level)
+				break;
+
+			parent = parent_commands;
+
+			/* Restore the status of the parent command. */
+			beentry->st_progress = parent->progress;
+
+			parent_commands = parent->parent;
+			pfree(parent);
+
+			/*
+			 * If only the top-level command remains in progress, clear the
+			 * top command info to indicate that there is no command above it.
+			 */
+			if (parent_commands == NULL)
+			{
+				beentry->st_progress_top.command = PROGRESS_COMMAND_INVALID;
+				beentry->st_progress_top.command_target = InvalidOid;
+				beentry->st_progress_top.xact_level = 0;
+				/* The top command should never become dummy, but be tidy. */
+				beentry->st_progress_top.is_dummy = false;
+			}
+		}
+		else
+		{
+			/*
+			 * End the top-level command. (Unless it belongs to parent
+			 * transaction.)
+			 */
+			if (!xact || beentry->st_progress.xact_level >= xact_level)
+			{
+				beentry->st_progress.command = PROGRESS_COMMAND_INVALID;
+				beentry->st_progress.command_target = InvalidOid;
+				beentry->st_progress.xact_level = 0;
+				/* See above. */
+				beentry->st_progress.is_dummy = false;
+			}
+
+			break;
+		}
+
+		/*
+		 * If this is not the end of transaction, the user is only interested
+		 * in ending the inner-most command.
+		 */
+		if (!xact)
+			break;
+	}
 	PGSTAT_END_WRITE_ACTIVITY(beentry);
 }
+
+/* XXX Define single function and a macro for each kind of callback? */
+void
+AtStart_BackendProgress(int nestingLevel)
+{
+	xact_level = nestingLevel;
+}
+
+void
+AtEOXact_BackendProgress(int nestingLevel)
+{
+	xact_level = nestingLevel;
+}
+
+void
+AtSubStart_BackendProgress(int nestingLevel)
+{
+	xact_level = nestingLevel;
+}
+
+void
+AtEOSubXact_BackendProgress(int nestingLevel)
+{
+	xact_level = nestingLevel;
+}
diff --git a/src/backend/utils/activity/backend_status.c b/src/backend/utils/activity/backend_status.c
index d685fc5cd87..004d152debd 100644
--- a/src/backend/utils/activity/backend_status.c
+++ b/src/backend/utils/activity/backend_status.c
@@ -283,8 +283,12 @@ pgstat_bestart_initial(void)
 	lbeentry.st_gss = false;
 
 	lbeentry.st_state = STATE_STARTING;
-	lbeentry.st_progress_command = PROGRESS_COMMAND_INVALID;
-	lbeentry.st_progress_command_target = InvalidOid;
+	lbeentry.st_progress.command = PROGRESS_COMMAND_INVALID;
+	lbeentry.st_progress.command_target = InvalidOid;
+	lbeentry.st_progress.xact_level = 0;
+	lbeentry.st_progress_top.command = PROGRESS_COMMAND_INVALID;
+	lbeentry.st_progress_top.command_target = InvalidOid;
+	lbeentry.st_progress_top.xact_level = 0; /* Not used. */
 	lbeentry.st_query_id = INT64CONST(0);
 	lbeentry.st_plan_id = INT64CONST(0);
 
diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 64b6f60516c..85510a1fe77 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -373,6 +373,7 @@ pg_stat_get_progress_info(PG_FUNCTION_ARGS)
 	{
 		LocalPgBackendStatus *local_beentry;
 		PgBackendStatus *beentry;
+		PgBackendProgress	*st_progress;
 		Datum		values[PG_STAT_GET_PROGRESS_COLS] = {0};
 		bool		nulls[PG_STAT_GET_PROGRESS_COLS] = {0};
 		int			i;
@@ -382,9 +383,18 @@ pg_stat_get_progress_info(PG_FUNCTION_ARGS)
 
 		/*
 		 * Report values for only those backends which are running the given
-		 * command.
+		 * command. (Dummy entry has no data to report.)
 		 */
-		if (beentry->st_progress_command != cmdtype)
+		if (!beentry->st_progress.is_dummy &&
+			beentry->st_progress.command == cmdtype)
+			st_progress = &beentry->st_progress;
+		else if (beentry->st_progress_top.command == cmdtype)
+		{
+			Assert(!beentry->st_progress_top.is_dummy);
+
+			st_progress = &beentry->st_progress_top;
+		}
+		else
 			continue;
 
 		/* Value available to all callers */
@@ -394,9 +404,9 @@ pg_stat_get_progress_info(PG_FUNCTION_ARGS)
 		/* show rest of the values including relid only to role members */
 		if (HAS_PGSTAT_PERMISSIONS(beentry->st_userid))
 		{
-			values[2] = ObjectIdGetDatum(beentry->st_progress_command_target);
+			values[2] = ObjectIdGetDatum(st_progress->command_target);
 			for (i = 0; i < PGSTAT_NUM_PROGRESS_PARAM; i++)
-				values[i + 3] = Int64GetDatum(beentry->st_progress_param[i]);
+				values[i + 3] = Int64GetDatum(st_progress->param[i]);
 		}
 		else
 		{
diff --git a/src/include/catalog/index.h b/src/include/catalog/index.h
index 5add66817cf..52f807394e0 100644
--- a/src/include/catalog/index.h
+++ b/src/include/catalog/index.h
@@ -45,9 +45,8 @@ typedef struct ReindexParams
 
 /* flag bits for ReindexParams->flags */
 #define REINDEXOPT_VERBOSE		0x01	/* print progress info */
-#define REINDEXOPT_REPORT_PROGRESS 0x02 /* report pgstat progress */
-#define REINDEXOPT_MISSING_OK 	0x04	/* skip missing relations */
-#define REINDEXOPT_CONCURRENTLY	0x08	/* concurrent mode */
+#define REINDEXOPT_MISSING_OK 	0x02	/* skip missing relations */
+#define REINDEXOPT_CONCURRENTLY	0x04	/* concurrent mode */
 
 /* state info for validate_index bulkdelete callback */
 typedef struct ValidateIndexState
@@ -71,8 +70,7 @@ extern void index_check_primary_key(Relation heapRel,
 #define	INDEX_CREATE_IF_NOT_EXISTS			(1 << 4)
 #define	INDEX_CREATE_PARTITIONED			(1 << 5)
 #define INDEX_CREATE_INVALID				(1 << 6)
-#define INDEX_CREATE_SUPPRESS_PROGRESS		(1 << 7)
-#define INDEX_CREATE_DEFERRABLE				(1 << 8)
+#define INDEX_CREATE_DEFERRABLE				(1 << 7)
 
 extern Oid	index_create(Relation heapRelation,
 						 const char *indexRelationName,
@@ -153,8 +151,7 @@ extern void index_build(Relation heapRelation,
 						Relation indexRelation,
 						IndexInfo *indexInfo,
 						bool isreindex,
-						bool parallel,
-						bool progress);
+						bool parallel);
 
 extern void validate_index(Oid heapId, Oid indexId, Snapshot snapshot);
 
diff --git a/src/include/utils/backend_progress.h b/src/include/utils/backend_progress.h
index 61e13c40e28..2afe77f285f 100644
--- a/src/include/utils/backend_progress.h
+++ b/src/include/utils/backend_progress.h
@@ -41,7 +41,11 @@ extern void pgstat_progress_incr_param(int index, int64 incr);
 extern void pgstat_progress_parallel_incr_param(int index, int64 incr);
 extern void pgstat_progress_update_multi_param(int nparam, const int *index,
 											   const int64 *val);
-extern void pgstat_progress_end_command(void);
+extern void pgstat_progress_end_command(bool xact);
+extern void AtStart_BackendProgress(int nestingLevel);
+extern void AtEOXact_BackendProgress(int nestingLevel);
+extern void AtSubStart_BackendProgress(int nestingLevel);
+extern void AtEOSubXact_BackendProgress(int nestingLevel);
 
 
 #endif							/* BACKEND_PROGRESS_H */
diff --git a/src/include/utils/backend_status.h b/src/include/utils/backend_status.h
index a334e096e4a..3c79f4ba72e 100644
--- a/src/include/utils/backend_status.h
+++ b/src/include/utils/backend_status.h
@@ -82,6 +82,36 @@ typedef struct PgBackendGSSStatus
 
 } PgBackendGSSStatus;
 
+/*
+ * Command progress reporting.  Any command which wishes can advertise that it
+ * is running by setting st_progress_command, st_progress_command_target, and
+ * st_progress_param[].  st_progress_command_target should be the OID of the
+ * relation which the command targets (we assume there's just one, as this is
+ * meant for utility commands), but the meaning of each element in the
+ * st_progress_param array is command-specific.
+ */
+typedef struct PgBackendProgress
+{
+	ProgressCommandType command;
+	Oid			command_target;
+	/* Transaction nesting level the monitoring started at. */
+	int			xact_level;
+
+	/*
+	 * If a backend tries to start monitoring of a command of and another
+	 * command of the same type is already being monitored, mark the new
+	 * command as dummy, so that it's not actually used. (We still need the
+	 * command in the stack so that pgstat_progress_end_command() works
+	 * correctly.)
+	 *
+	 * The typical scenario is COPY TO running on a table having an insert
+	 * trigger that scans a file_fdw table (which in turn runs COPY FROM). In
+	 * this case, we can only monitor the "outer" COPY TO.
+	 */
+	bool		is_dummy;
+
+	int64		param[PGSTAT_NUM_PROGRESS_PARAM];
+} PgBackendProgress;
 
 /* ----------
  * PgBackendStatus
@@ -156,18 +186,13 @@ typedef struct PgBackendStatus
 	 */
 	char	   *st_activity_raw;
 
+	/* Command progress reporting. */
+	PgBackendProgress st_progress;
 	/*
-	 * Command progress reporting.  Any command which wishes can advertise
-	 * that it is running by setting st_progress_command,
-	 * st_progress_command_target, and st_progress_param[].
-	 * st_progress_command_target should be the OID of the relation which the
-	 * command targets (we assume there's just one, as this is meant for
-	 * utility commands), but the meaning of each element in the
-	 * st_progress_param array is command-specific.
+	 * If a subcommand is being monitored, the command that triggered it is
+	 * reported here.
 	 */
-	ProgressCommandType st_progress_command;
-	Oid			st_progress_command_target;
-	int64		st_progress_param[PGSTAT_NUM_PROGRESS_PARAM];
+	PgBackendProgress	st_progress_top;
 
 	/* query identifier, optionally computed using post_parse_analyze_hook */
 	int64		st_query_id;
@@ -290,6 +315,10 @@ typedef struct LocalPgBackendStatus
 extern PGDLLIMPORT bool pgstat_track_activities;
 extern PGDLLIMPORT int pgstat_track_activity_query_size;
 
+/*
+ * This is to turn off progress tracking while pgstat_track_activities is on.
+ */
+extern bool pgstat_track_progress;
 
 /* ----------
  * Other global variables
diff --git a/src/test/modules/injection_points/Makefile b/src/test/modules/injection_points/Makefile
index a7a16d5016a..45bdbffec37 100644
--- a/src/test/modules/injection_points/Makefile
+++ b/src/test/modules/injection_points/Makefile
@@ -21,6 +21,7 @@ WAIT_CLEANUP_TST = $(if $(filter win32,$(PORTNAME)),,wait_cleanup)
 
 ISOLATION = basic \
 	    inplace \
+	    progress \
 	    reindex_concurrently_deferred \
 	    reindex_concurrently_toast \
 	    repack \
diff --git a/src/test/modules/injection_points/expected/progress.out b/src/test/modules/injection_points/expected/progress.out
new file mode 100644
index 00000000000..6319dcd8456
--- /dev/null
+++ b/src/test/modules/injection_points/expected/progress.out
@@ -0,0 +1,68 @@
+Parsed test spec with 4 sessions
+
+starting permutation: repack_wait check_index wakeup
+injection_points_set_local
+--------------------------
+                          
+(1 row)
+
+injection_points_set_local
+--------------------------
+                          
+(1 row)
+
+step repack_wait: 
+        SELECT injection_points_attach('progress-end-command-nested', 'wait');
+        REPACK progress_test;
+ <waiting ...>
+step check_index: 
+        SELECT command FROM pg_stat_progress_create_index;
+
+command
+-------
+REINDEX
+(1 row)
+
+step wakeup: 
+        SELECT injection_points_wakeup('progress-end-command-nested');
+
+injection_points_wakeup
+-----------------------
+                       
+(1 row)
+
+step repack_wait: <... completed>
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+
+starting permutation: repack_error check_repack
+injection_points_set_local
+--------------------------
+                          
+(1 row)
+
+injection_points_set_local
+--------------------------
+                          
+(1 row)
+
+step repack_error: 
+        SELECT injection_points_attach('progress-update-param-nested', 'error');
+        REPACK progress_test;
+
+injection_points_attach
+-----------------------
+                       
+(1 row)
+
+ERROR:  error triggered for injection point progress-update-param-nested
+step check_repack: 
+        SELECT command FROM pg_stat_progress_repack;
+
+command
+-------
+(0 rows)
+
diff --git a/src/test/modules/injection_points/meson.build b/src/test/modules/injection_points/meson.build
index cf9cb219548..ac37b52eed9 100644
--- a/src/test/modules/injection_points/meson.build
+++ b/src/test/modules/injection_points/meson.build
@@ -29,6 +29,7 @@ test_install_data += files(
 injection_points_isolation = [
   'basic',
   'inplace',
+  'progress',
   'reindex_concurrently_deferred',
   'reindex_concurrently_toast',
   'repack',
diff --git a/src/test/modules/injection_points/specs/progress.spec b/src/test/modules/injection_points/specs/progress.spec
new file mode 100644
index 00000000000..17d8222daa0
--- /dev/null
+++ b/src/test/modules/injection_points/specs/progress.spec
@@ -0,0 +1,66 @@
+# Test progress reporting of subcommands.
+setup
+{
+        CREATE EXTENSION injection_points;
+        CREATE TABLE progress_test(i int primary key);
+}
+
+teardown
+{
+        DROP TABLE progress_test;
+        DROP EXTENSION injection_points;
+}
+
+session s1
+setup
+{
+        SELECT injection_points_set_local();
+}
+# REPACK is suitable because it reports progress itself and it also runs
+# another progress reporting command (CREATE_INDEX).
+step repack_wait
+{
+        SELECT injection_points_attach('progress-end-command-nested', 'wait');
+        REPACK progress_test;
+}
+
+session s2
+step check_index
+{
+        SELECT command FROM pg_stat_progress_create_index;
+}
+step wakeup
+{
+        SELECT injection_points_wakeup('progress-end-command-nested');
+}
+
+session s3
+setup
+{
+        SELECT injection_points_set_local();
+}
+step repack_error
+{
+        SELECT injection_points_attach('progress-update-param-nested', 'error');
+        REPACK progress_test;
+}
+
+session s4
+step check_repack
+{
+        SELECT command FROM pg_stat_progress_repack;
+}
+
+
+# Wait just before ending the subcommand's progress reporting and check that
+# it's the index creation.
+permutation
+repack_wait
+check_index
+wakeup
+
+# If a subcommand ends up with ERROR, the backend's progress reporting state
+# must be cleaned up properly.
+permutation
+repack_error
+check_repack
diff --git a/src/tools/pgindent/typedefs.list b/src/tools/pgindent/typedefs.list
index f10eb469266..90a434201eb 100644
--- a/src/tools/pgindent/typedefs.list
+++ b/src/tools/pgindent/typedefs.list
@@ -2275,6 +2275,8 @@ PgAioWorkerSlot
 PgAioWorkerSubmissionQueue
 PgArchData
 PgBackendGSSStatus
+PgBackendProgress
+PgBackendProgresElt
 PgBackendSSLStatus
 PgBackendStatus
 PgBenchExpr
-- 
2.51.0

