26.4. Отслеживание выполнения #

В Postgres Pro имеется возможность отслеживать выполнение определённых команд. В настоящее время такое отслеживание поддерживается только для команд ANALYZE, CLUSTER, CREATE INDEX, VACUUM, COPY и BASE_BACKUP (то есть для команды репликации, которую выполняет pg_basebackup). В будущем эта поддержка может быть расширена.

26.4.1. Отслеживание выполнения ANALYZE #

Во время выполнения ANALYZE представление pg_stat_progress_analyze будет содержать по одной строке для каждого обслуживающего процесса, выполняющего эту команду. Таблицы ниже показывают, какая информация будет отслеживаться, и поясняют, как её интерпретировать.

Таблица 26.37. Представление pg_stat_progress_analyze

Тип столбца

Описание

pid integer

Идентификатор (PID) обслуживающего процесса

datid oid

OID базы данных, к которой подключён этот обслуживающий процесс.

datname name

Имя базы данных, к которой подключён этот обслуживающий процесс.

relid oid

OID анализируемой таблицы.

phase text

Текущая фаза обработки. См. Таблицу 26.38.

sample_blks_total bigint

Общее количество блоков кучи, которые попадут в выборку.

sample_blks_scanned bigint

Количество просканированных блоков кучи.

ext_stats_total bigint

Количество объектов расширенной статистики.

ext_stats_computed bigint

Количество вычисленных объектов расширенной статистики. Этот счётчик увеличивается только в фазе computing extended statistics (вычисление расширенной статистики).

child_tables_total bigint

Количество дочерних таблиц.

child_tables_done bigint

Количество просканированных дочерних таблиц. Этот счётчик увеличивается только в фазе acquiring inherited sample rows (извлечение строк выборки через наследование).

current_child_table_relid oid

OID дочерней таблицы, сканируемой в данный момент. Это поле содержит актуальное значение только в фазе acquiring inherited sample rows (извлечение строк выборки через наследование).


Таблица 26.38. Фазы ANALYZE

ФазаОписание
initializingКоманда готовится начать сканирование кучи. Эта фаза должна быть очень быстрой.
acquiring sample rowsКоманда сканирует таблицу с указанным relid, считывая строки выборки.
acquiring inherited sample rowsКоманда сканирует дочерние таблицы, считывая строки выборки. Выполнение процедуры в этой фазе отражается в столбцах child_tables_total, child_tables_done и current_child_table_relid.
computing statisticsКоманда вычисляет статистику по строкам выборки, полученным при сканировании таблицы.
computing extended statisticsКоманда вычисляет расширенную статистику по строкам выборки, полученным при сканировании таблицы.
finalizing analyzeКоманда вносит изменения в pg_class. После этой фазы ANALYZE завершит работу.

Примечание

Заметьте, что когда ANALYZE обрабатывает секционированную таблицу, все её секции также рекурсивно анализируются. В этом случае сначала сообщается о ходе выполнения ANALYZE для родительской таблицы, которое сопровождается сбором наследуемой статистики, а затем о ходе обработки каждой её секции.

26.4.2. Отслеживание выполнения CLUSTER #

Во время выполнения CLUSTER или VACUUM FULL представление pg_stat_progress_cluster будет содержать по одной строке для каждого обслуживающего процесса, выполняющего любую из этих команд. Таблицы ниже показывают, какая информация будет отслеживаться, и поясняют, как её интерпретировать.

Таблица 26.39. Представление pg_stat_progress_cluster

Тип столбца

Описание

pid integer

Идентификатор (PID) обслуживающего процесса

datid oid

OID базы данных, к которой подключён этот обслуживающий процесс.

datname name

Имя базы данных, к которой подключён этот обслуживающий процесс.

relid oid

OID обрабатываемой таблицы.

command text

Выполняемая команда: CLUSTER или VACUUM FULL.

phase text

Текущая фаза обработки. См. Таблицу 26.40.

cluster_index_relid oid

Если таблица сканируется по индексу, это поле содержит OID данного индекса, а иначе — 0.

heap_tuples_scanned bigint

Число просканированных кортежей кучи. Этот счётчик увеличивается только в фазе seq scanning heap, index scanning heap или writing new heap.

heap_tuples_written bigint

Число записанных кортежей кучи. Этот счётчик увеличивается только в фазе seq scanning heap, index scanning heap или writing new heap.

heap_blks_total bigint

Общее число блоков кучи в таблице. Это число отражает состояние в начале фазы seq scanning heap.

heap_blks_scanned bigint

Число просканированных блоков кучи. Этот счётчик увеличивается только в фазе seq scanning heap.

index_rebuild_count bigint

Число перестроенных индексов. Это счётчик увеличивается только в фазе rebuilding index.


Таблица 26.40. Фазы CLUSTER и VACUUM FULL

ФазаОписание
initializingКоманда готовится начать сканирование кучи. Эта фаза должна быть очень быстрой.
seq scanning heapКоманда в данный момент сканирует таблицу последовательным образом.
index scanning heapCLUSTER в данный момент сканирует таблицу по индексу.
sorting tuplesCLUSTER в данный момент сортирует кортежи.
writing new heapCLUSTER в данный момент записывает новую кучу.
swapping relation filesКоманда в данный момент переставляет только что построенные файлы на место.
rebuilding indexКоманда в данный момент перестраивает индекс.
performing final cleanupКоманда выполняет окончательную очистку. После этой фазы CLUSTER или VACUUM FULL завершит работу.

26.4.3. Отслеживание выполнения COPY #

Во время выполнения COPY представление pg_stat_progress_copy будет содержать по одной строке для каждого обслуживающего процесса, выполняющего эту команду. Таблицы ниже показывают, какая информация будет отслеживаться, и поясняют, как её интерпретировать.

Таблица 26.41. Представление pg_stat_progress_copy

Тип столбца

Описание

pid integer

Идентификатор (PID) обслуживающего процесса

datid oid

OID базы данных, к которой подключён этот обслуживающий процесс.

datname name

Имя базы данных, к которой подключён этот обслуживающий процесс.

relid oid

OID таблицы, в которой выполняется команда COPY. При копировании из запроса SELECT это поле содержит 0.

command text

Выполняемая команда: COPY FROM или COPY TO.

type text

Метод ввода/вывода, посредством которого считываются или записываются данные: FILE, PROGRAM, PIPE (для COPY FROM STDIN и COPY TO STDOUT) или CALLBACK (используется, например, во время начальной синхронизации таблицы при логической репликации).

bytes_processed bigint

Число байт, уже обработанных командой COPY.

bytes_total bigint

Размер исходного файла для команды COPY FROM в байтах. Если определить размер нельзя, это поле содержит 0.

tuples_processed bigint

Число кортежей, уже обработанных командой COPY.

tuples_excluded bigint

Количество необработанных кортежей, которые были исключены предложением WHERE команды COPY.


26.4.4. Отслеживание выполнения CREATE INDEX #

Во время выполнения CREATE INDEX или REINDEX представление pg_stat_progress_create_index будет содержать по одной строке для каждого обслуживающего процесса, создающего индексы в этот момент. Таблицы ниже показывают, какая информация будет отслеживаться, и поясняют, как её интерпретировать.

Таблица 26.42. Представление pg_stat_progress_create_index

Тип столбца

Описание

pid integer

Идентификатор серверного процесса, создающего индексы.

datid oid

OID базы данных, к которой подключён этот обслуживающий процесс.

datname name

Имя базы данных, к которой подключён этот обслуживающий процесс.

relid oid

OID таблицы, в которой создаётся индекс.

index_relid oid

OID создаваемого или перестраиваемого индекса. При выполнении CREATE INDEX в неблокирующем режиме содержит 0.

command text

Определённый тип команды: CREATE INDEX, CREATE INDEX CONCURRENTLY, REINDEX или REINDEX CONCURRENTLY.

phase text

Текущая фаза создания индекса. См. Таблицу 26.43.

lockers_total bigint

Общее число процессов, потребовавших ожидания, если таковые имеются.

lockers_done bigint

Число процессов, ожидание которых уже завершено.

current_locker_pid bigint

Идентификатор процесса, удерживающего конфликтующую блокировку в данный момент.

blocks_total bigint

Общее число блоков, которые должны быть обработаны в текущей фазе.

blocks_done bigint

Число блоков, уже обработанных в текущей фазе.

tuples_total bigint

Общее число кортежей, которые должны быть обработаны в текущей фазе.

tuples_done bigint

Число кортежей, уже обработанных в текущей фазе.

partitions_total bigint

Общее количество секций, для которых должен быть создан или прикреплён индекс, включая как прямые, так и косвенные секции. Имеет значение 0, когда выполняется REINDEX или если индекс не секционирован.

partitions_done bigint

Количество секций, для которых уже был создан или прикреплён индекс, включая как прямые, так и косвенные секции. Имеет значение 0, когда выполняется REINDEX или если индекс не секционирован.


Таблица 26.43. Фазы CREATE INDEX

ФазаОписание
initializingИнициализация — процедура CREATE INDEX или REINDEX подготавливается к созданию индекса. Эта фаза должна быть очень быстрой.
waiting for writers before buildОжидание окончания записи перед построением — процедура CREATE INDEX CONCURRENTLY или REINDEX CONCURRENTLY ожидает завершения транзакций, которые удерживают блокировки записи и могут читать таблицу. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах lockers_total, lockers_done и current_locker_pid.
building indexПостроение индекса — код, реализующий метод доступа, строит индекс. В этой фазе методы доступа, поддерживающие отслеживание процесса, передают свои данные о текущем состоянии, и в этом столбце видна внутренняя фаза. Обычно ход построения индекса отражается в столбцах blocks_total и blocks_done, но также могут меняться и столбцы tuples_total и tuples_done.
waiting for writers before validationОжидание окончания записи перед проверкой — процедура CREATE INDEX CONCURRENTLY или REINDEX CONCURRENTLY ожидает завершения транзакций, которые удерживают блокировки записи и могут записывать в таблицу. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах lockers_total, lockers_done и current_locker_pid.
index validation: scanning indexПроверка индекса: сканирование — процедура CREATE INDEX CONCURRENTLY сканирует индекс, находя кортежи, требующие проверки. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах blocks_total (показывающем общий размер индекса) и blocks_done.
index validation: sorting tuplesПроверка индекса: сортировка кортежей — процедура CREATE INDEX CONCURRENTLY сортирует результат фазы сканирования индекса.
index validation: scanning tableПроверка индекса: сканирование таблицы — процедура CREATE INDEX CONCURRENTLY сканирует таблицу, чтобы проверить кортежи индекса, собранные в предыдущих двух фазах. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах blocks_total (показывающем общий размер таблицы) и blocks_done.
waiting for old snapshotsОжидание старых снимков — процедура CREATE INDEX CONCURRENTLY или REINDEX CONCURRENTLY ожидает освобождения снимков теми транзакциями, которые могут видеть содержимое таблицы. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах lockers_total, lockers_done и current_locker_pid.
waiting for readers before marking deadОжидание завершения чтения перед отключением старого индекса — процедура REINDEX CONCURRENTLY ожидает завершения транзакций, которые удерживают блокировки чтения, прежде чем пометить старый индекс как нерабочий. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах lockers_total, lockers_done и current_locker_pid.
waiting for readers before droppingОжидание завершения чтения перед удалением старого индекса — процедура REINDEX CONCURRENTLY ожидает завершения транзакций, которые удерживают блокировки чтения, прежде чем удалить старый индекс. Эта фаза пропускается при выполнении операции в неблокирующем режиме. Выполнение процедуры в этой фазе отражается в столбцах lockers_total, lockers_done и current_locker_pid.

26.4.5. Отслеживание выполнения VACUUM #

В процессе выполнения VACUUM представление pg_stat_progress_vacuum будет содержать по одной строке для каждого обслуживающего процесса (включая рабочие процессы автоочистки), производящего очистку в данный момент. Таблицы ниже показывают, какая информация будет отслеживаться, и поясняют, как её интерпретировать. Выполнение команд VACUUM FULL отслеживается через pg_stat_progress_cluster, так как и VACUUM FULL, и CLUSTER перезаписывают таблицу, тогда как обычная команда VACUUM модифицирует её саму. См. Подраздел 26.4.2.

Таблица 26.44. Представление pg_stat_progress_vacuum

Тип столбца

Описание

pid integer

Идентификатор (PID) обслуживающего процесса

datid oid

OID базы данных, к которой подключён этот обслуживающий процесс.

datname name

Имя базы данных, к которой подключён этот обслуживающий процесс.

relid oid

OID очищаемой таблицы.

phase text

Текущая фаза очистки. См. Таблицу 26.45.

heap_blks_total bigint

Общее число блоков кучи в таблице. Это число отражает состояние в начале сканирования; блоки, добавленные позже, не будут (и не должны) обрабатываться текущей командой VACUUM.

heap_blks_scanned bigint

Число просканированных блоков кучи. Так как для оптимизации сканирования применяется карта видимости, некоторые блоки могут пропускаться без осмотра; пропущенные блоки входят в это общее число, так что по завершении очистки это число станет равно heap_blks_total. Этот счётчик увеличивается только в фазе scanning heap.

heap_blks_vacuumed bigint

Число очищенных блоков кучи. Если в таблице нет индексов, этот счётчик увеличивается только в фазе vacuuming heap (очистка кучи). Блоки, не содержащие «мёртвых» кортежей, при этом пропускаются, так что этот счётчик иногда может увеличиваться резкими рывками.

index_vacuum_count bigint

Количество завершённых циклов очистки индекса.

max_dead_tuples bigint

Число «мёртвых» кортежей, которое мы можем сохранить, прежде чем потребуется выполнить цикл очистки индекса, в зависимости от maintenance_work_mem.

num_dead_tuples bigint

Число «мёртвых» кортежей, собранных со времени последнего цикла очистки индекса.


Таблица 26.45. Фазы VACUUM

ФазаОписание
initializingИнициализация — VACUUM готовится начать сканирование кучи. Эта фаза должна быть очень быстрой.
scanning heapСканирование кучи — VACUUM в настоящее время сканирует кучу. При этом будет очищена и, если требуется, дефрагментирована каждая страница, а возможно, также будет произведена заморозка. Отслеживать процесс сканирования можно, следя за содержимым столбца heap_blks_scanned.
vacuuming indexesОчистка индексов — VACUUM в настоящее время очищает индексы. Если у таблицы есть какие-либо индексы, эта фаза будет наблюдаться минимум единожды в процессе очистки, после того, как куча будет просканирована полностью. Она может повторяться несколько раз в процессе очистки, если объёма maintenance_work_mem (или, в случае автоочистки, autovacuum_work_mem, если он задан) оказывается недостаточно для сохранения всех найденных «мёртвых» кортежей.
vacuuming heapОчистка кучи — VACUUM в настоящее время очищает кучу. Очистка кучи отличается от сканирования, так как она происходит после каждой операции очистки индексов. Если heap_blks_scanned меньше чем heap_blks_total, система вернётся к сканированию кучи после завершения этой фазы; в противном случае она начнёт уборку индексов.
cleaning up indexesУборка индексов — VACUUM в настоящее время производит уборку в индексах. Это происходит после завершения полного сканирования кучи и очистки индексов и кучи.
truncating heapУсечение кучи — VACUUM в настоящее время усекает кучу, чтобы возвратить операционной системе объём пустых страниц в конце отношения. Это происходит после уборки индексов.
performing final cleanupВыполнение окончательной очистки — VACUUM выполняет окончательную очистку. На этой стадии VACUUM очищает карту свободного пространства, обновляет статистику в pg_class и передаёт информацию системе накопительной статистики. После этой фазы VACUUM завершит свою работу.

26.4.6. Отслеживание выполнение базового копирования #

Когда приложение pg_basebackup или подобное выполняет базовое копирование, представление pg_stat_progress_basebackup будет содержать по одной строке для каждого процесса-передатчика WAL, выполняющего в данный момент команду репликации BASE_BACKUP и передающего копируемые данные. Таблицы ниже показывают, какая информация будет отслеживаться, и поясняют, как её интерпретировать.

Таблица 26.46. Представление pg_stat_progress_basebackup

Тип столбца

Описание

pid integer

Идентификатор процесса-передатчика WAL.

phase text

Текущая фаза обработки. См. Таблицу 26.47.

backup_total bigint

Общий объём данных, который будет передан. Оценка этого объёма выдаётся на момент начала фазы streaming database files (передача файлов данных). Заметьте, что это лишь приблизительная оценка, так как база данных может измениться в фазе streaming database files и в резервную копию позже может быть добавлен WAL. Это значение устанавливается равным backup_streamed, когда фактически переданный объём начинает превышать рассчитанный предварительно. Когда расчёт оценки в pg_basebackup отключён (то есть передан параметр --no-estimate-size), это поле содержит NULL.

backup_streamed bigint

Объём переданных данных. Этот показатель увеличивается только в фазе streaming database files (передача файлов данных) или transferring wal files (передача файлов WAL).

tablespaces_total bigint

Общее число табличных пространств, которые будут переданы.

tablespaces_streamed bigint

Число переданных табличных пространств. Этот счётчик увеличивается только в фазе streaming database files (передача файлов данных).


Таблица 26.47. Фазы базового копирования

ФазаОписание
initializingПроцесс-передатчик WAL готовится начать копирование. Эта фаза должна быть очень быстрой.
waiting for checkpoint to finishПроцесс-передатчик WAL в настоящий момент выполняет pg_backup_start, чтобы подготовиться к получению базовой копии, и ждёт завершения контрольной точки для начала копирования.
estimating backup sizeПроцесс-передатчик WAL в настоящий момент оценивает общее количество файлов данных, которые будут передаваться при создании базовой копии.
streaming database filesПроцесс-передатчик WAL в настоящий момент передаёт файлы данных в качестве содержимого базовой резервной копии.
waiting for wal archiving to finishПроцесс-передатчик WAL в настоящий момент выполняет pg_backup_stop, чтобы закончить копирование, и ждёт успешного завершения архивации всех файлов WAL, необходимых для базовой копии. Если при запуске pg_basebackup был указан параметр --wal-method=none или --wal-method=stream, резервное копирования заканчивается сразу после данной фазы.
transferring wal filesПроцесс-передатчик WAL в настоящее время переносит все файлы WAL, заполненные во время копирования. Эта фаза следует за фазой waiting for wal archiving to finish, только если при запуске pg_basebackup указывался параметр --wal-method=fetch. По окончании этой фазы резервное копирование завершается.

26.4. Progress Reporting #

Postgres Pro has the ability to report the progress of certain commands during command execution. Currently, the only commands which support progress reporting are ANALYZE, CLUSTER, CREATE INDEX, VACUUM, COPY, and BASE_BACKUP (i.e., replication command that pg_basebackup issues to take a base backup). This may be expanded in the future.

26.4.1. ANALYZE Progress Reporting #

Whenever ANALYZE is running, the pg_stat_progress_analyze view will contain a row for each backend that is currently running that command. The tables below describe the information that will be reported and provide information about how to interpret it.

Table 26.37. pg_stat_progress_analyze View

Column Type

Description

pid integer

Process ID of backend.

datid oid

OID of the database to which this backend is connected.

datname name

Name of the database to which this backend is connected.

relid oid

OID of the table being analyzed.

phase text

Current processing phase. See Table 26.38.

sample_blks_total bigint

Total number of heap blocks that will be sampled.

sample_blks_scanned bigint

Number of heap blocks scanned.

ext_stats_total bigint

Number of extended statistics.

ext_stats_computed bigint

Number of extended statistics computed. This counter only advances when the phase is computing extended statistics.

child_tables_total bigint

Number of child tables.

child_tables_done bigint

Number of child tables scanned. This counter only advances when the phase is acquiring inherited sample rows.

current_child_table_relid oid

OID of the child table currently being scanned. This field is only valid when the phase is acquiring inherited sample rows.


Table 26.38. ANALYZE Phases

PhaseDescription
initializing The command is preparing to begin scanning the heap. This phase is expected to be very brief.
acquiring sample rows The command is currently scanning the table given by relid to obtain sample rows.
acquiring inherited sample rows The command is currently scanning child tables to obtain sample rows. Columns child_tables_total, child_tables_done, and current_child_table_relid contain the progress information for this phase.
computing statistics The command is computing statistics from the sample rows obtained during the table scan.
computing extended statistics The command is computing extended statistics from the sample rows obtained during the table scan.
finalizing analyze The command is updating pg_class. When this phase is completed, ANALYZE will end.

Note

Note that when ANALYZE is run on a partitioned table, all of its partitions are also recursively analyzed. In that case, ANALYZE progress is reported first for the parent table, whereby its inheritance statistics are collected, followed by that for each partition.

26.4.2. CLUSTER Progress Reporting #

Whenever CLUSTER or VACUUM FULL is running, the pg_stat_progress_cluster view will contain a row for each backend that is currently running either command. The tables below describe the information that will be reported and provide information about how to interpret it.

Table 26.39. pg_stat_progress_cluster View

Column Type

Description

pid integer

Process ID of backend.

datid oid

OID of the database to which this backend is connected.

datname name

Name of the database to which this backend is connected.

relid oid

OID of the table being clustered.

command text

The command that is running. Either CLUSTER or VACUUM FULL.

phase text

Current processing phase. See Table 26.40.

cluster_index_relid oid

If the table is being scanned using an index, this is the OID of the index being used; otherwise, it is zero.

heap_tuples_scanned bigint

Number of heap tuples scanned. This counter only advances when the phase is seq scanning heap, index scanning heap or writing new heap.

heap_tuples_written bigint

Number of heap tuples written. This counter only advances when the phase is seq scanning heap, index scanning heap or writing new heap.

heap_blks_total bigint

Total number of heap blocks in the table. This number is reported as of the beginning of seq scanning heap.

heap_blks_scanned bigint

Number of heap blocks scanned. This counter only advances when the phase is seq scanning heap.

index_rebuild_count bigint

Number of indexes rebuilt. This counter only advances when the phase is rebuilding index.


Table 26.40. CLUSTER and VACUUM FULL Phases

PhaseDescription
initializing The command is preparing to begin scanning the heap. This phase is expected to be very brief.
seq scanning heap The command is currently scanning the table using a sequential scan.
index scanning heapCLUSTER is currently scanning the table using an index scan.
sorting tuplesCLUSTER is currently sorting tuples.
writing new heapCLUSTER is currently writing the new heap.
swapping relation files The command is currently swapping newly-built files into place.
rebuilding index The command is currently rebuilding an index.
performing final cleanup The command is performing final cleanup. When this phase is completed, CLUSTER or VACUUM FULL will end.

26.4.3. COPY Progress Reporting #

Whenever COPY is running, the pg_stat_progress_copy view will contain one row for each backend that is currently running a COPY command. The table below describes the information that will be reported and provides information about how to interpret it.

Table 26.41. pg_stat_progress_copy View

Column Type

Description

pid integer

Process ID of backend.

datid oid

OID of the database to which this backend is connected.

datname name

Name of the database to which this backend is connected.

relid oid

OID of the table on which the COPY command is executed. It is set to 0 if copying from a SELECT query.

command text

The command that is running: COPY FROM, or COPY TO.

type text

The io type that the data is read from or written to: FILE, PROGRAM, PIPE (for COPY FROM STDIN and COPY TO STDOUT), or CALLBACK (used for example during the initial table synchronization in logical replication).

bytes_processed bigint

Number of bytes already processed by COPY command.

bytes_total bigint

Size of source file for COPY FROM command in bytes. It is set to 0 if not available.

tuples_processed bigint

Number of tuples already processed by COPY command.

tuples_excluded bigint

Number of tuples not processed because they were excluded by the WHERE clause of the COPY command.


26.4.4. CREATE INDEX Progress Reporting #

Whenever CREATE INDEX or REINDEX is running, the pg_stat_progress_create_index view will contain one row for each backend that is currently creating indexes. The tables below describe the information that will be reported and provide information about how to interpret it.

Table 26.42. pg_stat_progress_create_index View

Column Type

Description

pid integer

Process ID of the backend creating indexes.

datid oid

OID of the database to which this backend is connected.

datname name

Name of the database to which this backend is connected.

relid oid

OID of the table on which the index is being created.

index_relid oid

OID of the index being created or reindexed. During a non-concurrent CREATE INDEX, this is 0.

command text

Specific command type: CREATE INDEX, CREATE INDEX CONCURRENTLY, REINDEX, or REINDEX CONCURRENTLY.

phase text

Current processing phase of index creation. See Table 26.43.

lockers_total bigint

Total number of lockers to wait for, when applicable.

lockers_done bigint

Number of lockers already waited for.

current_locker_pid bigint

Process ID of the locker currently being waited for.

blocks_total bigint

Total number of blocks to be processed in the current phase.

blocks_done bigint

Number of blocks already processed in the current phase.

tuples_total bigint

Total number of tuples to be processed in the current phase.

tuples_done bigint

Number of tuples already processed in the current phase.

partitions_total bigint

Total number of partitions on which the index is to be created or attached, including both direct and indirect partitions. 0 during a REINDEX, or when the index is not partitioned.

partitions_done bigint

Number of partitions on which the index has already been created or attached, including both direct and indirect partitions. 0 during a REINDEX, or when the index is not partitioned.


Table 26.43. CREATE INDEX Phases

PhaseDescription
initializingCREATE INDEX or REINDEX is preparing to create the index. This phase is expected to be very brief.
waiting for writers before buildCREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY is waiting for transactions with write locks that can potentially see the table to finish. This phase is skipped when not in concurrent mode. Columns lockers_total, lockers_done and current_locker_pid contain the progress information for this phase.
building index The index is being built by the access method-specific code. In this phase, access methods that support progress reporting fill in their own progress data, and the subphase is indicated in this column. Typically, blocks_total and blocks_done will contain progress data, as well as potentially tuples_total and tuples_done.
waiting for writers before validationCREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY is waiting for transactions with write locks that can potentially write into the table to finish. This phase is skipped when not in concurrent mode. Columns lockers_total, lockers_done and current_locker_pid contain the progress information for this phase.
index validation: scanning indexCREATE INDEX CONCURRENTLY is scanning the index searching for tuples that need to be validated. This phase is skipped when not in concurrent mode. Columns blocks_total (set to the total size of the index) and blocks_done contain the progress information for this phase.
index validation: sorting tuplesCREATE INDEX CONCURRENTLY is sorting the output of the index scanning phase.
index validation: scanning tableCREATE INDEX CONCURRENTLY is scanning the table to validate the index tuples collected in the previous two phases. This phase is skipped when not in concurrent mode. Columns blocks_total (set to the total size of the table) and blocks_done contain the progress information for this phase.
waiting for old snapshotsCREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY is waiting for transactions that can potentially see the table to release their snapshots. This phase is skipped when not in concurrent mode. Columns lockers_total, lockers_done and current_locker_pid contain the progress information for this phase.
waiting for readers before marking deadREINDEX CONCURRENTLY is waiting for transactions with read locks on the table to finish, before marking the old index dead. This phase is skipped when not in concurrent mode. Columns lockers_total, lockers_done and current_locker_pid contain the progress information for this phase.
waiting for readers before droppingREINDEX CONCURRENTLY is waiting for transactions with read locks on the table to finish, before dropping the old index. This phase is skipped when not in concurrent mode. Columns lockers_total, lockers_done and current_locker_pid contain the progress information for this phase.

26.4.5. VACUUM Progress Reporting #

Whenever VACUUM is running, the pg_stat_progress_vacuum view will contain one row for each backend (including autovacuum worker processes) that is currently vacuuming. The tables below describe the information that will be reported and provide information about how to interpret it. Progress for VACUUM FULL commands is reported via pg_stat_progress_cluster because both VACUUM FULL and CLUSTER rewrite the table, while regular VACUUM only modifies it in place. See Section 26.4.2.

Table 26.44. pg_stat_progress_vacuum View

Column Type

Description

pid integer

Process ID of backend.

datid oid

OID of the database to which this backend is connected.

datname name

Name of the database to which this backend is connected.

relid oid

OID of the table being vacuumed.

phase text

Current processing phase of vacuum. See Table 26.45.

heap_blks_total bigint

Total number of heap blocks in the table. This number is reported as of the beginning of the scan; blocks added later will not be (and need not be) visited by this VACUUM.

heap_blks_scanned bigint

Number of heap blocks scanned. Because the visibility map is used to optimize scans, some blocks will be skipped without inspection; skipped blocks are included in this total, so that this number will eventually become equal to heap_blks_total when the vacuum is complete. This counter only advances when the phase is scanning heap.

heap_blks_vacuumed bigint

Number of heap blocks vacuumed. Unless the table has no indexes, this counter only advances when the phase is vacuuming heap. Blocks that contain no dead tuples are skipped, so the counter may sometimes skip forward in large increments.

index_vacuum_count bigint

Number of completed index vacuum cycles.

max_dead_tuples bigint

Number of dead tuples that we can store before needing to perform an index vacuum cycle, based on maintenance_work_mem.

num_dead_tuples bigint

Number of dead tuples collected since the last index vacuum cycle.


Table 26.45. VACUUM Phases

PhaseDescription
initializingVACUUM is preparing to begin scanning the heap. This phase is expected to be very brief.
scanning heapVACUUM is currently scanning the heap. It will prune and defragment each page if required, and possibly perform freezing activity. The heap_blks_scanned column can be used to monitor the progress of the scan.
vacuuming indexesVACUUM is currently vacuuming the indexes. If a table has any indexes, this will happen at least once per vacuum, after the heap has been completely scanned. It may happen multiple times per vacuum if maintenance_work_mem (or, in the case of autovacuum, autovacuum_work_mem if set) is insufficient to store the number of dead tuples found.
vacuuming heapVACUUM is currently vacuuming the heap. Vacuuming the heap is distinct from scanning the heap, and occurs after each instance of vacuuming indexes. If heap_blks_scanned is less than heap_blks_total, the system will return to scanning the heap after this phase is completed; otherwise, it will begin cleaning up indexes after this phase is completed.
cleaning up indexesVACUUM is currently cleaning up indexes. This occurs after the heap has been completely scanned and all vacuuming of the indexes and the heap has been completed.
truncating heapVACUUM is currently truncating the heap so as to return empty pages at the end of the relation to the operating system. This occurs after cleaning up indexes.
performing final cleanupVACUUM is performing final cleanup. During this phase, VACUUM will vacuum the free space map, update statistics in pg_class, and report statistics to the cumulative statistics system. When this phase is completed, VACUUM will end.

26.4.6. Base Backup Progress Reporting #

Whenever an application like pg_basebackup is taking a base backup, the pg_stat_progress_basebackup view will contain a row for each WAL sender process that is currently running the BASE_BACKUP replication command and streaming the backup. The tables below describe the information that will be reported and provide information about how to interpret it.

Table 26.46. pg_stat_progress_basebackup View

Column Type

Description

pid integer

Process ID of a WAL sender process.

phase text

Current processing phase. See Table 26.47.

backup_total bigint

Total amount of data that will be streamed. This is estimated and reported as of the beginning of streaming database files phase. Note that this is only an approximation since the database may change during streaming database files phase and WAL log may be included in the backup later. This is always the same value as backup_streamed once the amount of data streamed exceeds the estimated total size. If the estimation is disabled in pg_basebackup (i.e., --no-estimate-size option is specified), this is NULL.

backup_streamed bigint

Amount of data streamed. This counter only advances when the phase is streaming database files or transferring wal files.

tablespaces_total bigint

Total number of tablespaces that will be streamed.

tablespaces_streamed bigint

Number of tablespaces streamed. This counter only advances when the phase is streaming database files.


Table 26.47. Base Backup Phases

PhaseDescription
initializing The WAL sender process is preparing to begin the backup. This phase is expected to be very brief.
waiting for checkpoint to finish The WAL sender process is currently performing pg_backup_start to prepare to take a base backup, and waiting for the start-of-backup checkpoint to finish.
estimating backup size The WAL sender process is currently estimating the total amount of database files that will be streamed as a base backup.
streaming database files The WAL sender process is currently streaming database files as a base backup.
waiting for wal archiving to finish The WAL sender process is currently performing pg_backup_stop to finish the backup, and waiting for all the WAL files required for the base backup to be successfully archived. If either --wal-method=none or --wal-method=stream is specified in pg_basebackup, the backup will end when this phase is completed.
transferring wal files The WAL sender process is currently transferring all WAL logs generated during the backup. This phase occurs after waiting for wal archiving to finish phase if --wal-method=fetch is specified in pg_basebackup. The backup will end when this phase is completed.