From 2a6ee8da130e220e26e4b5c601df968759620903 Mon Sep 17 00:00:00 2001 From: Michael Paquier Date: Tue, 28 Jan 2025 09:57:32 +0900 Subject: [PATCH 01/20] Track per-relation cumulative time spent in [auto]vacuum and [auto]analyze This commit adds four fields to the statistics of relations, aggregating the amount of time spent for each operation on a relation: - total_vacuum_time, for manual vacuum. - total_autovacuum_time, for vacuum done by the autovacuum daemon. - total_analyze_time, for manual analyze. - total_autoanalyze_time, for analyze done by the autovacuum daemon. This gives users the option to derive the average time spent for these operations with the help of the related "count" fields. Bump PGSTAT_FILE_FORMAT_ID for the additions in PgStat_StatTabEntry. Catalog functions, views and their version bump follow separately. Author: Sami Imseih Reviewed-by: Bertrand Drouvot, Michael Paquier Discussion: https://postgr.es/m/CAA5RZ0uVOGBYmPEeGF2d1B_67tgNjKx_bKDuL+oUftuoz+=Y1g@mail.gmail.com (cherry picked from commit 30a6ed0ce4bb18212ec38cdb537ea4b43bc99b83) Cloudberry adaptation: time AO vacuum from its first phase and pass the start timestamp to the collector at final cleanup, so the changed API is usable by heap and AO immediately. Co-authored-by: Alena Rybakina --- src/backend/access/heap/vacuumlazy.c | 6 ++++-- src/backend/commands/analyze.c | 13 ++++++++---- src/backend/commands/vacuum_ao.c | 9 ++++++++- src/backend/utils/activity/pgstat_relation.c | 21 ++++++++++++++++---- src/include/access/appendonly_compaction.h | 3 +++ src/include/pgstat.h | 13 ++++++++---- 6 files changed, 50 insertions(+), 15 deletions(-) diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c index cf97d85df5d..f6d5bdc31c0 100644 --- a/src/backend/access/heap/vacuumlazy.c +++ b/src/backend/access/heap/vacuumlazy.c @@ -498,7 +498,6 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, if (instrument) { pg_rusage_init(&ru0); - starttime = GetCurrentTimestamp(); if (track_io_timing) { startreadtime = pgStatBlockReadTime; @@ -506,6 +505,8 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, } } + /* Used for instrumentation and stats report */ + starttime = GetCurrentTimestamp(); extVacCounters = extvac_stats_start(rel, verbose); pgstat_progress_start_command(PROGRESS_COMMAND_VACUUM, @@ -783,7 +784,8 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, rel->rd_rel->relisshared, Max(vacrel->new_live_tuples, 0), vacrel->recently_dead_tuples + - vacrel->missed_dead_tuples); + vacrel->missed_dead_tuples, + starttime); pgstat_progress_end_command(); if (instrument) diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index 194f49ee164..258390cf8d2 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -542,7 +542,10 @@ do_analyze_rel(Relation onerel, VacuumParams *params, save_sec_context | SECURITY_RESTRICTED_OPERATION); save_nestlevel = NewGUCNestLevel(); - /* measure elapsed time iff autovacuum logging requires it */ + /* + * When autovacuum logging is used, initialize a resource usage snapshot + * and optionally track I/O timing. + */ if (IsAutoVacuumWorkerProcess() && params->log_min_duration >= 0) { if (track_io_timing) @@ -552,9 +555,11 @@ do_analyze_rel(Relation onerel, VacuumParams *params, } pg_rusage_init(&ru0); - starttime = GetCurrentTimestamp(); } + /* Used for instrumentation and stats report */ + starttime = GetCurrentTimestamp(); + /* * Determine which columns to analyze * @@ -1223,9 +1228,9 @@ do_analyze_rel(Relation onerel, VacuumParams *params, */ if (!inh) pgstat_report_analyze(onerel, totalrows, totaldeadrows, - (va_cols == NIL)); + (va_cols == NIL), starttime); else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) - pgstat_report_analyze(onerel, 0, 0, (va_cols == NIL)); + pgstat_report_analyze(onerel, 0, 0, (va_cols == NIL), starttime); /* * If this isn't part of VACUUM ANALYZE, let index AMs do cleanup. diff --git a/src/backend/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c index 49503087aa9..c8f63f4a0e4 100644 --- a/src/backend/commands/vacuum_ao.c +++ b/src/backend/commands/vacuum_ao.c @@ -312,7 +312,8 @@ ao_vacuum_rel_post_cleanup(Relation onerel, VacuumParams *params, BufferAccessSt pgstat_report_vacuum(RelationGetRelid(onerel), onerel->rd_rel->relisshared, reltuples, - deadtuples); + deadtuples, + vacrelstats->starttime); SIMPLE_FAULT_INJECTOR("vacuum_ao_post_cleanup_end"); } @@ -424,6 +425,12 @@ init_vacrelstats(bool instrument) vacrelstats->extstats = palloc0(sizeof(AOVacuumExtStats)); MemoryContextSwitchTo(old_context); + /* + * The phases of an AO vacuum run as separate steps, all of them sharing + * these stats; time the vacuum from the first one. + */ + vacrelstats->starttime = GetCurrentTimestamp(); + return vacrelstats; } diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c index 45bbf9abcb7..0a47a18e638 100644 --- a/src/backend/utils/activity/pgstat_relation.c +++ b/src/backend/utils/activity/pgstat_relation.c @@ -215,19 +215,22 @@ pgstat_drop_relation(Relation rel) */ void pgstat_report_vacuum(Oid tableoid, bool shared, - PgStat_Counter livetuples, PgStat_Counter deadtuples) + PgStat_Counter livetuples, PgStat_Counter deadtuples, + TimestampTz starttime) { PgStat_EntryRef *entry_ref; PgStatShared_Relation *shtabentry; PgStat_StatTabEntry *tabentry; Oid dboid = (shared ? InvalidOid : MyDatabaseId); TimestampTz ts; + PgStat_Counter elapsedtime; if (!pgstat_track_counts) return; /* Store the data in the table's hash table entry. */ ts = GetCurrentTimestamp(); + elapsedtime = TimestampDifferenceMilliseconds(starttime, ts); /* block acquiring lock for the same reason as pgstat_report_autovac() */ entry_ref = pgstat_get_entry_ref_locked(PGSTAT_KIND_RELATION, @@ -255,11 +258,13 @@ pgstat_report_vacuum(Oid tableoid, bool shared, { tabentry->last_autovacuum_time = ts; tabentry->autovacuum_count++; + tabentry->total_autovacuum_time += elapsedtime; } else { tabentry->last_vacuum_time = ts; tabentry->vacuum_count++; + tabentry->total_vacuum_time += elapsedtime; } pgstat_unlock_entry(entry_ref); @@ -282,12 +287,14 @@ pgstat_report_vacuum(Oid tableoid, bool shared, void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, - bool resetcounter) + bool resetcounter, TimestampTz starttime) { PgStat_EntryRef *entry_ref; PgStatShared_Relation *shtabentry; PgStat_StatTabEntry *tabentry; Oid dboid = (rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId); + TimestampTz ts; + PgStat_Counter elapsedtime; if (!pgstat_track_counts) return; @@ -321,6 +328,10 @@ pgstat_report_analyze(Relation rel, deadtuples = Max(deadtuples, 0); } + /* Store the data in the table's hash table entry. */ + ts = GetCurrentTimestamp(); + elapsedtime = TimestampDifferenceMilliseconds(starttime, ts); + /* block acquiring lock for the same reason as pgstat_report_autovac() */ entry_ref = pgstat_get_entry_ref_locked(PGSTAT_KIND_RELATION, dboid, RelationGetRelid(rel), @@ -344,13 +355,15 @@ pgstat_report_analyze(Relation rel, if (IsAutoVacuumWorkerProcess()) { - tabentry->last_autoanalyze_time = GetCurrentTimestamp(); + tabentry->last_autoanalyze_time = ts; tabentry->autoanalyze_count++; + tabentry->total_autoanalyze_time += elapsedtime; } else { - tabentry->last_analyze_time = GetCurrentTimestamp(); + tabentry->last_analyze_time = ts; tabentry->analyze_count++; + tabentry->total_analyze_time += elapsedtime; } pgstat_unlock_entry(entry_ref); diff --git a/src/include/access/appendonly_compaction.h b/src/include/access/appendonly_compaction.h index 83746b406ef..f5fbc98bd4f 100644 --- a/src/include/access/appendonly_compaction.h +++ b/src/include/access/appendonly_compaction.h @@ -14,6 +14,7 @@ #define APPENDONLY_COMPACTION_H #include "pgstat.h" +#include "datatype/timestamp.h" #include "nodes/pg_list.h" #include "access/appendonly_visimap.h" #include "utils/rel.h" @@ -39,6 +40,8 @@ typedef struct AOVacuumRelStats int nbytes_truncated; /* current # of bytes truncated from segment file */ int num_dead_tuples; /* current # of dead tuples */ int num_index_vacuumed; /* current # of indexes been vacuumed */ + /* when the first phase started, for the cumulative vacuum time */ + TimestampTz starttime; /* the relation these stats were started for */ Oid relid; /* Index resources are excluded from each phase's VERBOSE report. */ diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 680b288ecdd..e059ffe29a7 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -233,7 +233,7 @@ typedef struct PgStat_TableXactStatus * ------------------------------------------------------------ */ -#define PGSTAT_FILE_FORMAT_ID 0x01A5BCC0 +#define PGSTAT_FILE_FORMAT_ID 0x01A5BCAE typedef struct PgStat_ArchiverStats { @@ -422,6 +422,11 @@ typedef struct PgStat_StatTabEntry PgStat_Counter analyze_count; TimestampTz last_autoanalyze_time; /* autovacuum initiated */ PgStat_Counter autoanalyze_count; + + PgStat_Counter total_vacuum_time; /* times in milliseconds */ + PgStat_Counter total_autovacuum_time; + PgStat_Counter total_analyze_time; + PgStat_Counter total_autoanalyze_time; } PgStat_StatTabEntry; typedef struct PgStat_WalStats @@ -646,11 +651,11 @@ extern void pgstat_assoc_relation(Relation rel); extern void pgstat_unlink_relation(Relation rel); extern void pgstat_report_vacuum(Oid tableoid, bool shared, - PgStat_Counter livetuples, PgStat_Counter deadtuples); - + PgStat_Counter livetuples, PgStat_Counter deadtuples, + TimestampTz starttime); extern void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, - bool resetcounter); + bool resetcounter, TimestampTz starttime); /* * If stats are enabled, but pending data hasn't been prepared yet, call From 954176f91e71aade99e1e1a387f6607bbbb727af Mon Sep 17 00:00:00 2001 From: Nathan Bossart Date: Tue, 11 Feb 2025 16:38:14 -0600 Subject: [PATCH 02/20] Add is_analyze parameter to vacuum_delay_point(). This function is used in both vacuum and analyze code paths, and a follow-up commit will require distinguishing between the two. This commit forces callers to specify whether they are in a vacuum or analyze path, but it does not use that information for anything yet. Author: Nathan Bossart Co-authored-by: Bertrand Drouvot Discussion: https://postgr.es/m/ZmaXmWDL829fzAVX%40ip-10-97-1-34.eu-west-3.compute.internal Backported from PostgreSQL 18 (commit e5b0b0ce150972bf162a059430d84e5f8e07cf30) as a prerequisite of the vacuum statistics series. Cloudberry adaptation: the append-optimized and AOCS sample-row acquisition and compaction call vacuum_delay_point() too; the former pass is_analyze = true, the latter false. --- contrib/bloom/blvacuum.c | 4 ++-- contrib/file_fdw/file_fdw.c | 2 +- src/backend/access/aocs/aocs_compaction.c | 2 +- src/backend/access/aocs/aocsam_handler.c | 2 +- src/backend/access/appendonly/appendonly_compaction.c | 2 +- src/backend/access/appendonly/appendonlyam_handler.c | 2 +- src/backend/access/gin/ginfast.c | 6 +++--- src/backend/access/gin/ginvacuum.c | 6 +++--- src/backend/access/gist/gistvacuum.c | 2 +- src/backend/access/hash/hash.c | 2 +- src/backend/access/heap/vacuumlazy.c | 6 +++--- src/backend/access/nbtree/nbtree.c | 2 +- src/backend/access/spgist/spgvacuum.c | 4 ++-- src/backend/commands/analyze.c | 10 +++++----- src/backend/commands/vacuum.c | 2 +- src/backend/tsearch/ts_typanalyze.c | 2 +- src/backend/utils/adt/array_typanalyze.c | 2 +- src/backend/utils/adt/rangetypes_typanalyze.c | 2 +- src/include/commands/vacuum.h | 2 +- 19 files changed, 31 insertions(+), 31 deletions(-) diff --git a/contrib/bloom/blvacuum.c b/contrib/bloom/blvacuum.c index 2340d49e00a..6a6609be16f 100644 --- a/contrib/bloom/blvacuum.c +++ b/contrib/bloom/blvacuum.c @@ -61,7 +61,7 @@ blbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, *itupPtr, *itupEnd; - vacuum_delay_point(); + vacuum_delay_point(false); buffer = ReadBufferExtended(index, MAIN_FORKNUM, blkno, RBM_NORMAL, info->strategy); @@ -191,7 +191,7 @@ blvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats) Buffer buffer; Page page; - vacuum_delay_point(); + vacuum_delay_point(false); buffer = ReadBufferExtended(index, MAIN_FORKNUM, blkno, RBM_NORMAL, info->strategy); diff --git a/contrib/file_fdw/file_fdw.c b/contrib/file_fdw/file_fdw.c index 70511892349..85212cb1148 100644 --- a/contrib/file_fdw/file_fdw.c +++ b/contrib/file_fdw/file_fdw.c @@ -1205,7 +1205,7 @@ file_acquire_sample_rows(Relation onerel, int elevel, for (;;) { /* Check for user-requested abort or sleep */ - vacuum_delay_point(); + vacuum_delay_point(true); /* Fetch next row */ MemoryContextReset(tupcontext); diff --git a/src/backend/access/aocs/aocs_compaction.c b/src/backend/access/aocs/aocs_compaction.c index 820a12e4619..e7be4f5a9f8 100644 --- a/src/backend/access/aocs/aocs_compaction.c +++ b/src/backend/access/aocs/aocs_compaction.c @@ -322,7 +322,7 @@ AOCSSegmentFileFullCompaction(Relation aorel, tupleCount++; if (VacuumCostActive && tupleCount % tuplePerPage == 0) { - vacuum_delay_point(); + vacuum_delay_point(false); } /* diff --git a/src/backend/access/aocs/aocsam_handler.c b/src/backend/access/aocs/aocsam_handler.c index 0b152e7204a..a1c827175f7 100644 --- a/src/backend/access/aocs/aocsam_handler.c +++ b/src/backend/access/aocs/aocsam_handler.c @@ -1680,7 +1680,7 @@ aoco_acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, { aocoscan->targrow = RowSampler_Next(&rs); - vacuum_delay_point(); + vacuum_delay_point(true); if (aocs_get_target_tuple(aocoscan, aocoscan->targrow, slot)) { diff --git a/src/backend/access/appendonly/appendonly_compaction.c b/src/backend/access/appendonly/appendonly_compaction.c index 2ded0c54975..c5a12b12f8d 100644 --- a/src/backend/access/appendonly/appendonly_compaction.c +++ b/src/backend/access/appendonly/appendonly_compaction.c @@ -507,7 +507,7 @@ AppendOnlySegmentFileFullCompaction(Relation aorel, tupleCount++; if (VacuumCostActive && tupleCount % tuplePerPage == 0) { - vacuum_delay_point(); + vacuum_delay_point(false); } } diff --git a/src/backend/access/appendonly/appendonlyam_handler.c b/src/backend/access/appendonly/appendonlyam_handler.c index 3e99bdf7202..79595425fe4 100644 --- a/src/backend/access/appendonly/appendonlyam_handler.c +++ b/src/backend/access/appendonly/appendonlyam_handler.c @@ -1557,7 +1557,7 @@ appendonly_acquire_sample_rows(Relation onerel, int elevel, HeapTuple *rows, { aoscan->targrow = RowSampler_Next(&rs); - vacuum_delay_point(); + vacuum_delay_point(true); if (appendonly_get_target_tuple(aoscan, aoscan->targrow, slot)) { diff --git a/src/backend/access/gin/ginfast.c b/src/backend/access/gin/ginfast.c index 2c23afe3a03..65b7f7ef3b7 100644 --- a/src/backend/access/gin/ginfast.c +++ b/src/backend/access/gin/ginfast.c @@ -891,7 +891,7 @@ ginInsertCleanup(GinState *ginstate, bool full_clean, */ processPendingPage(&accum, &datums, page, FirstOffsetNumber); - vacuum_delay_point(); + vacuum_delay_point(false); /* * Is it time to flush memory to disk? Flush if we are at the end of @@ -928,7 +928,7 @@ ginInsertCleanup(GinState *ginstate, bool full_clean, { ginEntryInsert(ginstate, attnum, key, category, list, nlist, NULL); - vacuum_delay_point(); + vacuum_delay_point(false); } /* @@ -1001,7 +1001,7 @@ ginInsertCleanup(GinState *ginstate, bool full_clean, /* * Read next page in pending list */ - vacuum_delay_point(); + vacuum_delay_point(false); buffer = ReadBuffer(index, blkno); LockBuffer(buffer, GIN_SHARE); page = BufferGetPage(buffer); diff --git a/src/backend/access/gin/ginvacuum.c b/src/backend/access/gin/ginvacuum.c index e5d310d8362..067224ab475 100644 --- a/src/backend/access/gin/ginvacuum.c +++ b/src/backend/access/gin/ginvacuum.c @@ -663,12 +663,12 @@ ginbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, UnlockReleaseBuffer(buffer); } - vacuum_delay_point(); + vacuum_delay_point(false); for (i = 0; i < nRoot; i++) { ginVacuumPostingTree(&gvs, rootOfPostingTree[i]); - vacuum_delay_point(); + vacuum_delay_point(false); } if (blkno == InvalidBlockNumber) /* rightmost page */ @@ -749,7 +749,7 @@ ginvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats) Buffer buffer; Page page; - vacuum_delay_point(); + vacuum_delay_point(false); buffer = ReadBufferExtended(index, MAIN_FORKNUM, blkno, RBM_NORMAL, info->strategy); diff --git a/src/backend/access/gist/gistvacuum.c b/src/backend/access/gist/gistvacuum.c index 3f60d3274d2..f6608b9c3cf 100644 --- a/src/backend/access/gist/gistvacuum.c +++ b/src/backend/access/gist/gistvacuum.c @@ -283,7 +283,7 @@ gistvacuumpage(GistVacState *vstate, BlockNumber blkno, BlockNumber orig_blkno) recurse_to = InvalidBlockNumber; /* call vacuum_delay_point while not holding any buffer lock */ - vacuum_delay_point(); + vacuum_delay_point(false); buffer = ReadBufferExtended(rel, MAIN_FORKNUM, blkno, RBM_NORMAL, info->strategy); diff --git a/src/backend/access/hash/hash.c b/src/backend/access/hash/hash.c index e50f117bcb9..bb5fd890d76 100644 --- a/src/backend/access/hash/hash.c +++ b/src/backend/access/hash/hash.c @@ -732,7 +732,7 @@ hashbucketcleanup(Relation rel, Bucket cur_bucket, Buffer bucket_buf, bool retain_pin = false; bool clear_dead_marking = false; - vacuum_delay_point(); + vacuum_delay_point(false); page = BufferGetPage(buf); opaque = HashPageGetOpaque(page); diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c index f6d5bdc31c0..d813749b1dc 100644 --- a/src/backend/access/heap/vacuumlazy.c +++ b/src/backend/access/heap/vacuumlazy.c @@ -1077,7 +1077,7 @@ lazy_scan_heap(LVRelState *vacrel) update_vacuum_error_info(vacrel, NULL, VACUUM_ERRCB_PHASE_SCAN_HEAP, blkno, InvalidOffsetNumber); - vacuum_delay_point(); + vacuum_delay_point(false); /* * Regularly check if wraparound failsafe should trigger. @@ -1540,7 +1540,7 @@ lazy_scan_skip(LVRelState *vacrel, Buffer *vmbuffer, BlockNumber next_block, skipsallvis = true; } - vacuum_delay_point(); + vacuum_delay_point(false); next_unskippable_block++; nskippable_blocks++; } @@ -2643,7 +2643,7 @@ lazy_vacuum_heap_rel(LVRelState *vacrel) Page page; Size freespace; - vacuum_delay_point(); + vacuum_delay_point(false); blkno = ItemPointerGetBlockNumber(&vacrel->dead_items->items[index]); vacrel->blkno = blkno; diff --git a/src/backend/access/nbtree/nbtree.c b/src/backend/access/nbtree/nbtree.c index 77106093030..7d06557642c 100644 --- a/src/backend/access/nbtree/nbtree.c +++ b/src/backend/access/nbtree/nbtree.c @@ -1169,7 +1169,7 @@ btvacuumpage(BTVacState *vstate, BlockNumber scanblkno) backtrack_to = P_NONE; /* call vacuum_delay_point while not holding any buffer lock */ - vacuum_delay_point(); + vacuum_delay_point(false); /* * We can't use _bt_getbuf() here because it always applies diff --git a/src/backend/access/spgist/spgvacuum.c b/src/backend/access/spgist/spgvacuum.c index 85bc02b92c8..1f0e98648b8 100644 --- a/src/backend/access/spgist/spgvacuum.c +++ b/src/backend/access/spgist/spgvacuum.c @@ -626,7 +626,7 @@ spgvacuumpage(spgBulkDeleteState *bds, BlockNumber blkno) Page page; /* call vacuum_delay_point while not holding any buffer lock */ - vacuum_delay_point(); + vacuum_delay_point(false); buffer = ReadBufferExtended(index, MAIN_FORKNUM, blkno, RBM_NORMAL, bds->info->strategy); @@ -705,7 +705,7 @@ spgprocesspending(spgBulkDeleteState *bds) continue; /* ignore already-done items */ /* call vacuum_delay_point while not holding any buffer lock */ - vacuum_delay_point(); + vacuum_delay_point(false); /* examine the referenced page */ blkno = ItemPointerGetBlockNumber(&pitem->tid); diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index 258390cf8d2..37d8c529c06 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -1429,7 +1429,7 @@ compute_index_stats(Relation onerel, double totalrows, { HeapTuple heapTuple = rows[rowno]; - vacuum_delay_point(); + vacuum_delay_point(true); /* * Reset the per-tuple context each time, to reclaim any cruft @@ -1849,7 +1849,7 @@ acquire_sample_rows(Relation onerel, int elevel, prefetch_targblock = BlockSampler_Next(&prefetch_bs); #endif - vacuum_delay_point(); + vacuum_delay_point(true); block_accepted = table_scan_analyze_next_block(scan, targblock, vac_strategy); @@ -3487,7 +3487,7 @@ compute_trivial_stats(VacAttrStatsP stats, Datum value; bool isnull; - vacuum_delay_point(); + vacuum_delay_point(true); value = fetchfunc(stats, i, &isnull); @@ -3609,7 +3609,7 @@ compute_distinct_stats(VacAttrStatsP stats, int firstcount1, j; - vacuum_delay_point(); + vacuum_delay_point(true); value = fetchfunc(stats, i, &isnull); @@ -3969,7 +3969,7 @@ compute_scalar_stats(VacAttrStatsP stats, Datum value; bool isnull; - vacuum_delay_point(); + vacuum_delay_point(true); value = fetchfunc(stats, i, &isnull); diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 0ec93b2152a..c876b4121ac 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -3146,7 +3146,7 @@ vac_close_indexes(int nindexes, Relation *Irel, LOCKMODE lockmode) * typically once per page processed. */ void -vacuum_delay_point(void) +vacuum_delay_point(bool is_analyze) { double msec = 0; diff --git a/src/backend/tsearch/ts_typanalyze.c b/src/backend/tsearch/ts_typanalyze.c index c24243b11b4..6aa685ed55f 100644 --- a/src/backend/tsearch/ts_typanalyze.c +++ b/src/backend/tsearch/ts_typanalyze.c @@ -206,7 +206,7 @@ compute_tsvector_stats(VacAttrStats *stats, char *lexemesptr; int j; - vacuum_delay_point(); + vacuum_delay_point(true); value = fetchfunc(stats, vector_no, &isnull); diff --git a/src/backend/utils/adt/array_typanalyze.c b/src/backend/utils/adt/array_typanalyze.c index 52e160d6bbb..2db192d7544 100644 --- a/src/backend/utils/adt/array_typanalyze.c +++ b/src/backend/utils/adt/array_typanalyze.c @@ -314,7 +314,7 @@ compute_array_stats(VacAttrStats *stats, AnalyzeAttrFetchFunc fetchfunc, int distinct_count; bool count_item_found; - vacuum_delay_point(); + vacuum_delay_point(true); value = fetchfunc(stats, array_no, &isnull); if (isnull) diff --git a/src/backend/utils/adt/rangetypes_typanalyze.c b/src/backend/utils/adt/rangetypes_typanalyze.c index ff8700e8e43..a3e98fcf766 100644 --- a/src/backend/utils/adt/rangetypes_typanalyze.c +++ b/src/backend/utils/adt/rangetypes_typanalyze.c @@ -169,7 +169,7 @@ compute_range_stats(VacAttrStats *stats, AnalyzeAttrFetchFunc fetchfunc, upper; float8 length; - vacuum_delay_point(); + vacuum_delay_point(true); value = fetchfunc(stats, range_no, &isnull); if (isnull) diff --git a/src/include/commands/vacuum.h b/src/include/commands/vacuum.h index f19205c584a..d70b026ec36 100644 --- a/src/include/commands/vacuum.h +++ b/src/include/commands/vacuum.h @@ -494,7 +494,7 @@ extern bool vacuum_get_cutoffs(Relation rel, const VacuumParams *params, struct VacuumCutoffs *cutoffs); extern bool vacuum_xid_failsafe_check(const struct VacuumCutoffs *cutoffs); extern void vac_update_datfrozenxid(void); -extern void vacuum_delay_point(void); +extern void vacuum_delay_point(bool is_analyze); extern bool vacuum_is_relation_owner(Oid relid, Form_pg_class reltuple, bits32 options); extern Relation vacuum_open_relation(Oid relid, RangeVar *relation, From fc2b88e4a81a579405db36dc4d095e2143a90c44 Mon Sep 17 00:00:00 2001 From: Nathan Bossart Date: Tue, 11 Feb 2025 16:38:14 -0600 Subject: [PATCH 03/20] Measure cost-based vacuum delay for progress reporting. This commit adds the amount of time spent sleeping due to cost-based delay to the pg_stat_progress_vacuum and pg_stat_progress_analyze system views. A new configuration parameter named track_cost_delay_timing, which is off by default, controls whether this information is gathered. SQL view definitions and the catalog version change are included in the native SQL reporting commit. Author: Bertrand Drouvot Co-authored-by: Nathan Bossart Reviewed-by: Sami Imseih Reviewed-by: Robert Haas Reviewed-by: Masahiko Sawada Reviewed-by: Masahiro Ikeda Reviewed-by: Dilip Kumar Reviewed-by: Sergei Kornilov Discussion: https://postgr.es/m/ZmaXmWDL829fzAVX%40ip-10-97-1-34.eu-west-3.compute.internal Backported from PostgreSQL 18 (commit bb8dff9995f2cf501376772898bcbcf58aa05cde) as a prerequisite of the vacuum statistics series. Cloudberry adaptation: the vacuum progress parameters of this branch end at num_dead_tuples, so the delay time is PROGRESS_VACUUM_DELAY_TIME 7 (param8 of the view). Cloudberry does not run parallel vacuum (see dead_items_alloc()), so omit the unused parallel-worker delay accumulator. Local progress reporting measures the VACUUM or ANALYZE backend's own cost delays. The new GUC is listed in unsync_guc_names_array, next to track_io_timing, as every GUC has to be in one of the two lists here. SQL progress-view changes are separated into the native SQL reporting commit; measurement, the GUC and progress counters are introduced here. --- src/backend/commands/vacuum.c | 24 +++++++++++++++++++ src/backend/utils/misc/guc_tables.c | 9 +++++++ src/backend/utils/misc/postgresql.conf.sample | 1 + src/include/commands/progress.h | 2 ++ src/include/commands/vacuum.h | 2 ++ src/include/utils/unsync_guc_name.h | 1 + 6 files changed, 39 insertions(+) diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index c876b4121ac..95de59441bd 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -47,6 +47,7 @@ #include "catalog/pg_namespace.h" #include "commands/cluster.h" #include "commands/defrem.h" +#include "commands/progress.h" #include "commands/tablecmds.h" #include "commands/vacuum.h" #include "miscadmin.h" @@ -106,6 +107,7 @@ int vacuum_multixact_freeze_min_age; int vacuum_multixact_freeze_table_age; int vacuum_failsafe_age; int vacuum_multixact_failsafe_age; +bool track_cost_delay_timing; /* * Variables for cost-based vacuum delay. The defaults differ between @@ -3189,13 +3191,35 @@ vacuum_delay_point(bool is_analyze) /* Nap if appropriate */ if (msec > 0) { + instr_time delay_start; + if (msec > vacuum_cost_delay * 4) msec = vacuum_cost_delay * 4; + if (track_cost_delay_timing) + INSTR_TIME_SET_CURRENT(delay_start); + pgstat_report_wait_start(WAIT_EVENT_VACUUM_DELAY); pg_usleep(msec * 1000); pgstat_report_wait_end(); + if (track_cost_delay_timing) + { + instr_time delay_end; + instr_time delay; + + INSTR_TIME_SET_CURRENT(delay_end); + INSTR_TIME_SET_ZERO(delay); + INSTR_TIME_ACCUM_DIFF(delay, delay_end, delay_start); + + if (is_analyze) + pgstat_progress_incr_param(PROGRESS_ANALYZE_DELAY_TIME, + INSTR_TIME_GET_NANOSEC(delay)); + else + pgstat_progress_incr_param(PROGRESS_VACUUM_DELAY_TIME, + INSTR_TIME_GET_NANOSEC(delay)); + } + /* * We don't want to ignore postmaster death during very long vacuums * with vacuum_cost_delay configured. We can't use the usual diff --git a/src/backend/utils/misc/guc_tables.c b/src/backend/utils/misc/guc_tables.c index bf6d2754e7b..8c699c27b90 100644 --- a/src/backend/utils/misc/guc_tables.c +++ b/src/backend/utils/misc/guc_tables.c @@ -1480,6 +1480,15 @@ struct config_bool ConfigureNamesBool[] = true, NULL, NULL, NULL }, + { + {"track_cost_delay_timing", PGC_SUSET, STATS_CUMULATIVE, + gettext_noop("Collects timing statistics for cost-based vacuum delay."), + NULL + }, + &track_cost_delay_timing, + false, + NULL, NULL, NULL + }, { {"track_io_timing", PGC_SUSET, STATS_CUMULATIVE, gettext_noop("Collects timing statistics for database I/O activity."), diff --git a/src/backend/utils/misc/postgresql.conf.sample b/src/backend/utils/misc/postgresql.conf.sample index 04cdb8f2b2a..02564d83cd4 100644 --- a/src/backend/utils/misc/postgresql.conf.sample +++ b/src/backend/utils/misc/postgresql.conf.sample @@ -649,6 +649,7 @@ optimizer_analyze_root_partition = on # stats collection on root partitions #track_activities = on #track_activity_query_size = 1024 # (change requires restart) #track_counts = off +#track_cost_delay_timing = off #track_io_timing = off #track_wal_io_timing = off #track_functions = none # none, pl, all diff --git a/src/include/commands/progress.h b/src/include/commands/progress.h index fc9ce7c1a66..01e0b766cd3 100644 --- a/src/include/commands/progress.h +++ b/src/include/commands/progress.h @@ -25,6 +25,7 @@ #define PROGRESS_VACUUM_NUM_INDEX_VACUUMS 4 #define PROGRESS_VACUUM_MAX_DEAD_TUPLES 5 #define PROGRESS_VACUUM_NUM_DEAD_TUPLES 6 +#define PROGRESS_VACUUM_DELAY_TIME 7 /* Phases of vacuum (as advertised via PROGRESS_VACUUM_PHASE) */ #define PROGRESS_VACUUM_PHASE_SCAN_HEAP 1 @@ -47,6 +48,7 @@ #define PROGRESS_ANALYZE_CHILD_TABLES_TOTAL 5 #define PROGRESS_ANALYZE_CHILD_TABLES_DONE 6 #define PROGRESS_ANALYZE_CURRENT_CHILD_TABLE_RELID 7 +#define PROGRESS_ANALYZE_DELAY_TIME 8 /* Phases of analyze (as advertised via PROGRESS_ANALYZE_PHASE) */ #define PROGRESS_ANALYZE_PHASE_ACQUIRE_SAMPLE_ROWS 1 diff --git a/src/include/commands/vacuum.h b/src/include/commands/vacuum.h index d70b026ec36..3cf576982cd 100644 --- a/src/include/commands/vacuum.h +++ b/src/include/commands/vacuum.h @@ -436,6 +436,7 @@ extern PGDLLIMPORT int vacuum_multixact_freeze_min_age; extern PGDLLIMPORT int vacuum_multixact_freeze_table_age; extern PGDLLIMPORT int vacuum_failsafe_age; extern PGDLLIMPORT int vacuum_multixact_failsafe_age; +extern PGDLLIMPORT bool track_cost_delay_timing; /* Variables for cost-based parallel vacuum */ extern PGDLLIMPORT pg_atomic_uint32 *VacuumSharedCostBalance; @@ -463,6 +464,7 @@ extern PGDLLIMPORT bool VacuumFailsafeActive; extern PGDLLIMPORT double vacuum_cost_delay; extern PGDLLIMPORT int vacuum_cost_limit; + /* in commands/vacuum.c */ extern void ExecVacuum(ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel, bool auto_stats); extern void vacuum(List *relations, VacuumParams *params, diff --git a/src/include/utils/unsync_guc_name.h b/src/include/utils/unsync_guc_name.h index 371f9b28292..0150204094c 100644 --- a/src/include/utils/unsync_guc_name.h +++ b/src/include/utils/unsync_guc_name.h @@ -623,6 +623,7 @@ "track_activities", "track_activity_query_size", "track_commit_timestamp", + "track_cost_delay_timing", /* instance-local, like track_io_timing */ "track_counts", "track_functions", "track_io_timing", From 6fd2affa613527bce7c5f99ba1d25cd2a6066465 Mon Sep 17 00:00:00 2001 From: Nathan Bossart Date: Tue, 11 Feb 2025 16:38:14 -0600 Subject: [PATCH 04/20] Measure cost-based vacuum delay Port the process-local VacuumDelayTime accumulator from the REL_2_STABLE commit. Accumulate measured cost-based VACUUM sleep time only while track_cost_delay_timing is enabled, excluding ANALYZE. Consumers take before/after differences to attribute delays to their own operations. The preceding PostgreSQL 18 progress-view backport already provides the GUC, its documentation, sample setting, unsynchronized registration and sleep timing. Reuse that measurement and preserve both VACUUM and ANALYZE progress reporting. Keep the accumulator in milliseconds as double to match this branch's cumulative timing consumers, rather than the source branch's int64 microseconds. Extract the accumulator from the index/database timing commit and fold in the ANALYZE exclusion previously included in the combined heap/index/AO measurements commit. The final branch contents are unchanged. Author: Bertrand Drouvot Discussion: https://postgr.es/m/ZmaXmWDL829fzAVX%40ip-10-97-1-34.eu-west-3.compute.internal Backported from PostgreSQL 18 (commit bb8dff9995f2cf501376772898bcbcf58aa05cde). (cherry picked from commit 01aaacbebf47548bde0f3521762fb643996d6094) Co-authored-by: Nathan Bossart Co-authored-by: Alena Rybakina --- src/backend/commands/vacuum.c | 9 +++++++++ src/include/commands/vacuum.h | 1 + 2 files changed, 10 insertions(+) diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 95de59441bd..0bc6cf39905 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -118,6 +118,13 @@ bool track_cost_delay_timing; double vacuum_cost_delay = 0; int vacuum_cost_limit = 200; +/* + * Cumulative cost-based VACUUM delay time (ms) for this process, excluding + * ANALYZE. + * Callers save the starting value and report the delta. + */ +double VacuumDelayTime = 0; + /* * VacuumFailsafeActive is a defined as a global so that we can determine * whether or not to re-enable cost-based vacuum delay when vacuuming a table. @@ -3211,6 +3218,8 @@ vacuum_delay_point(bool is_analyze) INSTR_TIME_SET_CURRENT(delay_end); INSTR_TIME_SET_ZERO(delay); INSTR_TIME_ACCUM_DIFF(delay, delay_end, delay_start); + if (!is_analyze) + VacuumDelayTime += INSTR_TIME_GET_MILLISEC(delay); if (is_analyze) pgstat_progress_incr_param(PROGRESS_ANALYZE_DELAY_TIME, diff --git a/src/include/commands/vacuum.h b/src/include/commands/vacuum.h index 3cf576982cd..08669efeeab 100644 --- a/src/include/commands/vacuum.h +++ b/src/include/commands/vacuum.h @@ -464,6 +464,7 @@ extern PGDLLIMPORT bool VacuumFailsafeActive; extern PGDLLIMPORT double vacuum_cost_delay; extern PGDLLIMPORT int vacuum_cost_limit; +extern PGDLLIMPORT double VacuumDelayTime; /* in commands/vacuum.c */ extern void ExecVacuum(ParseState *pstate, VacuumStmt *vacstmt, bool isTopLevel, bool auto_stats); From 464707f80b6e0248a94b0ca852a76c2cf2240a66 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Mon, 21 Sep 2026 01:40:05 +0300 Subject: [PATCH 05/20] Measure append-optimized vacuum active-phase time Accumulate elapsed time and cost-based delays over active AO vacuum phases, excluding the gaps between phases. Discard state left over from an interrupted operation. Prepare per-index timing measurements for the subsequent cumulative-reporting change. Adapted-from: 6f38fb242db39b4df922687265f9651bb115b35a --- src/backend/commands/vacuum_ao.c | 66 ++++++++++++++++++---- src/include/access/appendonly_compaction.h | 12 +++- 2 files changed, 65 insertions(+), 13 deletions(-) diff --git a/src/backend/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c index c8f63f4a0e4..47dc09592f6 100644 --- a/src/backend/commands/vacuum_ao.c +++ b/src/backend/commands/vacuum_ao.c @@ -114,6 +114,8 @@ */ #include "postgres.h" +#include + #include "access/table.h" #include "access/aocs_compaction.h" #include "access/aomd.h" @@ -157,7 +159,7 @@ static bool appendonly_tid_reaped(ItemPointer itemptr, void *state); static void vacuum_appendonly_fill_stats(Relation aorel, Snapshot snapshot, int elevel, BlockNumber *rel_pages, double *rel_tuples, - double *dead_tuples, bool *relhasindex, BlockNumber *total_file_segs); + int64 *dead_tuples, bool *relhasindex, BlockNumber *total_file_segs); static int vacuum_appendonly_indexes(Relation aoRelation, int options, Bitmapset *dead_segs, BufferAccessStrategy bstrategy, AOVacuumRelStats *vacrelstats); static void ao_vacuum_rel_recycle_dead_segments(Relation onerel, VacuumParams *params, @@ -169,6 +171,8 @@ static void ao_accum_resources(PgStat_CommonCounts *dst, static void ao_measure_index_resources(Relation indrel, LVExtStatCounters *counters, AOVacuumRelStats *vacrelstats, bool verbose); +static void ao_measure_index_vacuum_time(Relation indrel, TimestampTz starttime, + double startdelaytime); static void ao_vacuum_rel_pre_cleanup(Relation onerel, VacuumParams *params, BufferAccessStrategy bstrategy, AOVacuumRelStats *vacrelstats) @@ -243,7 +247,7 @@ ao_vacuum_rel_post_cleanup(Relation onerel, VacuumParams *params, BufferAccessSt { BlockNumber relpages; double reltuples; - double deadtuples; + int64 deadtuples; bool relhasindex; /* AO/AOCO total file segment number, use type BlockNumber to * represent same type with num_all_visible_pages in libpq. @@ -308,6 +312,10 @@ ao_vacuum_rel_post_cleanup(Relation onerel, VacuumParams *params, BufferAccessSt false, true /* isvacuum */); + /* Report once all phase timers have been stopped. */ + vacrelstats->live_tuples = reltuples; + vacrelstats->dead_tuples = deadtuples; + /* report results to the stats collector, too */ pgstat_report_vacuum(RelationGetRelid(onerel), onerel->rd_rel->relisshared, @@ -315,6 +323,7 @@ ao_vacuum_rel_post_cleanup(Relation onerel, VacuumParams *params, BufferAccessSt deadtuples, vacrelstats->starttime); + SIMPLE_FAULT_INJECTOR("vacuum_ao_post_cleanup_end"); } @@ -423,13 +432,8 @@ init_vacrelstats(bool instrument) vacrelstats = (AOVacuumRelStats *) palloc0(sizeof(AOVacuumRelStats)); if (instrument) vacrelstats->extstats = palloc0(sizeof(AOVacuumExtStats)); - MemoryContextSwitchTo(old_context); - - /* - * The phases of an AO vacuum run as separate steps, all of them sharing - * these stats; time the vacuum from the first one. - */ vacrelstats->starttime = GetCurrentTimestamp(); + MemoryContextSwitchTo(old_context); return vacrelstats; } @@ -446,6 +450,9 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy LVExtStatCounters *extcounters; bool verbose = (params->options & VACOPT_VERBOSE) != 0; PgStat_CommonCounts index_start = {0}; + instr_time phase_start; + instr_time phase_end; + double phase_start_delay; Assert(RelationStorageIsAO(rel)); Assert(params != NULL); @@ -491,6 +498,9 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy if (vacrelstats->extstats != NULL) index_start = vacrelstats->extstats->indexes; + INSTR_TIME_SET_CURRENT(phase_start); + phase_start_delay = VacuumDelayTime; + /* * Do the actual work --- either FULL or "lazy" vacuum */ @@ -529,6 +539,14 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy } } + if (ao_vacuum_phase != 0) + { + INSTR_TIME_SET_CURRENT(phase_end); + INSTR_TIME_SUBTRACT(phase_end, phase_start); + vacrelstats->vacuum_time += INSTR_TIME_GET_MILLISEC(phase_end); + vacrelstats->delay_time += VacuumDelayTime - phase_start_delay; + } + if (ao_vacuum_phase == VACOPT_AO_POST_CLEANUP_PHASE) { pgstat_progress_end_command(); @@ -648,6 +666,24 @@ ao_measure_index_resources(Relation indrel, LVExtStatCounters *counters, pfree(counters); } +/* + * Accumulate one vacuum pass over an index of an append-optimized table + * into the index's cumulative vacuum and delay times, as the heap does in + * lazy_vacuum_one_index() and lazy_cleanup_one_index(). + */ +static void +ao_measure_index_vacuum_time(Relation indrel, TimestampTz starttime, + double startdelaytime) +{ + PgStat_Counter elapsedtime = + TimestampDifferenceMilliseconds(starttime, GetCurrentTimestamp()); + PgStat_Counter delaytime = (PgStat_Counter) rint(VacuumDelayTime - startdelaytime); + + /* Backend-local measurements; cumulative reporting follows separately. */ + (void) elapsedtime; + (void) delaytime; +} + /* * Recycling AWAITING_DROP segments. */ @@ -722,6 +758,8 @@ vacuum_appendonly_indexes(Relation aoRelation, int options, Bitmapset *dead_segs int i; Relation *Irel; int nindexes; + bool final_cleanup = + (options & VACUUM_AO_PHASE_MASK) == VACOPT_AO_POST_CLEANUP_PHASE; Assert(RelationStorageIsAO(aoRelation)); @@ -752,6 +790,9 @@ vacuum_appendonly_indexes(Relation aoRelation, int options, Bitmapset *dead_segs { for (i = 0; i < nindexes; i++) { + TimestampTz istarttime = GetCurrentTimestamp(); + double startdelaytime = VacuumDelayTime; + LVExtStatCounters *extcounters; extcounters = extvac_stats_start(Irel[i], elevel == INFO); @@ -763,12 +804,16 @@ vacuum_appendonly_indexes(Relation aoRelation, int options, Bitmapset *dead_segs ao_measure_index_resources(Irel[i], extcounters, vacrelstats, elevel == INFO && Gp_role != GP_ROLE_DISPATCH); + ao_measure_index_vacuum_time(Irel[i], istarttime, startdelaytime); } } else { for (i = 0; i < nindexes; i++) { + TimestampTz istarttime = GetCurrentTimestamp(); + double startdelaytime = VacuumDelayTime; + LVExtStatCounters *extcounters; extcounters = extvac_stats_start(Irel[i], elevel == INFO); @@ -782,13 +827,14 @@ vacuum_appendonly_indexes(Relation aoRelation, int options, Bitmapset *dead_segs ao_measure_index_resources(Irel[i], extcounters, vacrelstats, elevel == INFO && Gp_role != GP_ROLE_DISPATCH); + ao_measure_index_vacuum_time(Irel[i], istarttime, startdelaytime); } } } vac_close_indexes(nindexes, Irel, NoLock); pgstat_progress_update_param(PROGRESS_VACUUM_PHASE, - ((options & VACUUM_AO_PHASE_MASK) == VACOPT_AO_POST_CLEANUP_PHASE) ? + final_cleanup ? PROGRESS_VACUUM_PHASE_AO_POST_CLEANUP : PROGRESS_VACUUM_PHASE_AO_PRE_CLEANUP); return nindexes; } @@ -906,7 +952,7 @@ appendonly_tid_reaped(ItemPointer itemptr, void *state) static void vacuum_appendonly_fill_stats(Relation aorel, Snapshot snapshot, int elevel, BlockNumber *rel_pages, double *rel_tuples, - double *dead_tuples, bool *relhasindex, BlockNumber *total_file_segs) + int64 *dead_tuples, bool *relhasindex, BlockNumber *total_file_segs) { FileSegTotals *fstotal; BlockNumber nblocks; diff --git a/src/include/access/appendonly_compaction.h b/src/include/access/appendonly_compaction.h index f5fbc98bd4f..5fd3b989cab 100644 --- a/src/include/access/appendonly_compaction.h +++ b/src/include/access/appendonly_compaction.h @@ -37,11 +37,17 @@ typedef struct AOVacuumExtStats */ typedef struct AOVacuumRelStats { - int nbytes_truncated; /* current # of bytes truncated from segment file */ - int num_dead_tuples; /* current # of dead tuples */ + int64 nbytes_truncated; /* current # of bytes truncated from segment file */ + int64 num_dead_tuples; /* current # of dead tuples */ int num_index_vacuumed; /* current # of indexes been vacuumed */ - /* when the first phase started, for the cumulative vacuum time */ + /* Legacy timing-report baseline, retained until elapsed-time reporting. */ TimestampTz starttime; + /* Active phase durations and delays in milliseconds, excluding phase gaps. */ + double vacuum_time; + double delay_time; + int64 live_tuples; + int64 dead_tuples; + /* the relation these stats were started for */ Oid relid; /* Index resources are excluded from each phase's VERBOSE report. */ From dc4b9b4b471cdfc9332ce17ce29cdca77ea1bf0e Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Thu, 1 Oct 2026 16:21:13 +0300 Subject: [PATCH 06/20] Accumulate vacuum timing for indexes and databases Record index-pass elapsed and cost-delay time, including parallel workers with the leader's autovacuum classification. Add cumulative table delay time and database totals without adding index time to database totals a second time. Include removed tuple counts in verbose index reports. Catalog getters, views, documentation and SQL-dependent tests follow in the separate native SQL reporting commit. --- src/backend/access/heap/vacuumlazy.c | 35 +++++++++- src/backend/commands/vacuum_ao.c | 3 +- src/backend/commands/vacuumparallel.c | 21 ++++++ src/backend/utils/activity/pgstat_database.c | 5 ++ src/backend/utils/activity/pgstat_relation.c | 68 +++++++++++++++++++- src/include/pgstat.h | 27 +++++++- 6 files changed, 153 insertions(+), 6 deletions(-) diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c index d813749b1dc..8c8a6b777c3 100644 --- a/src/backend/access/heap/vacuumlazy.c +++ b/src/backend/access/heap/vacuumlazy.c @@ -487,6 +487,7 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, PgStat_Counter startreadtime = 0, startwritetime = 0; LVExtStatCounters *extVacCounters; + double startdelaytime; WalUsage startwalusage = pgWalUsage; BufferUsage startbufferusage = pgBufferUsage; ErrorContextCallback errcallback; @@ -507,6 +508,7 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, /* Used for instrumentation and stats report */ starttime = GetCurrentTimestamp(); + startdelaytime = VacuumDelayTime; extVacCounters = extvac_stats_start(rel, verbose); pgstat_progress_start_command(PROGRESS_COMMAND_VACUUM, @@ -780,12 +782,20 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, pfree(extVacCounters); pfree(vacrel->extVacReportIdx); } + + /* + * The delay counter covers the whole heap_vacuum_rel() run, matching the + * scope of total_vacuum_time. In a parallel vacuum it covers the + * leader's sleeps only; parallel workers account their own sleeps to the + * indexes they process. + */ pgstat_report_vacuum(RelationGetRelid(rel), rel->rd_rel->relisshared, Max(vacrel->new_live_tuples, 0), vacrel->recently_dead_tuples + vacrel->missed_dead_tuples, - starttime); + starttime, + (PgStat_Counter) rint(VacuumDelayTime - startdelaytime)); pgstat_progress_end_command(); if (instrument) @@ -920,8 +930,9 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, continue; appendStringInfo(&buf, - _("index \"%s\": pages: %u in total, %u newly deleted, %u currently deleted, %u reusable\n"), + _("index \"%s\": tuples: %.0f removed; pages: %u in total, %u newly deleted, %u currently deleted, %u reusable\n"), indnames[i], + istat->tuples_removed, istat->num_pages, istat->pages_newly_deleted, istat->pages_deleted, @@ -2935,6 +2946,8 @@ lazy_vacuum_one_index(Relation indrel, IndexBulkDeleteResult *istat, IndexVacuumInfo ivinfo; LVSavedErrInfo saved_err_info; LVExtStatCounters *extVacCounters; + TimestampTz istarttime = GetCurrentTimestamp(); + double startdelaytime = VacuumDelayTime; extVacCounters = extvac_stats_start(indrel, vacrel->verbose); ivinfo.index = indrel; @@ -2972,6 +2985,14 @@ lazy_vacuum_one_index(Relation indrel, IndexBulkDeleteResult *istat, pfree(extVacCounters); } + /* Accumulate this pass into the index's cumulative vacuum times */ + pgstat_report_index_vacuum_time(indrel, + TimestampDifferenceMilliseconds(istarttime, + GetCurrentTimestamp()), + (PgStat_Counter) rint(VacuumDelayTime - + startdelaytime), + IsAutoVacuumWorkerProcess()); + /* Revert to the previous phase information for error traceback */ restore_vacuum_error_info(vacrel, &saved_err_info); pfree(vacrel->indname); @@ -2997,6 +3018,8 @@ lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat, IndexVacuumInfo ivinfo; LVSavedErrInfo saved_err_info; LVExtStatCounters *extVacCounters; + TimestampTz istarttime = GetCurrentTimestamp(); + double startdelaytime = VacuumDelayTime; extVacCounters = extvac_stats_start(indrel, vacrel->verbose); ivinfo.index = indrel; @@ -3034,6 +3057,14 @@ lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat, pfree(extVacCounters); } + /* Accumulate this pass into the index's cumulative vacuum times */ + pgstat_report_index_vacuum_time(indrel, + TimestampDifferenceMilliseconds(istarttime, + GetCurrentTimestamp()), + (PgStat_Counter) rint(VacuumDelayTime - + startdelaytime), + IsAutoVacuumWorkerProcess()); + /* Revert to the previous phase information for error traceback */ restore_vacuum_error_info(vacrel, &saved_err_info); pfree(vacrel->indname); diff --git a/src/backend/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c index 47dc09592f6..be2f58b1f61 100644 --- a/src/backend/commands/vacuum_ao.c +++ b/src/backend/commands/vacuum_ao.c @@ -321,7 +321,8 @@ ao_vacuum_rel_post_cleanup(Relation onerel, VacuumParams *params, BufferAccessSt onerel->rd_rel->relisshared, reltuples, deadtuples, - vacrelstats->starttime); + vacrelstats->starttime, + 0); /* AO delay time tracking is added in a later commit. */ SIMPLE_FAULT_INJECTOR("vacuum_ao_post_cleanup_end"); diff --git a/src/backend/commands/vacuumparallel.c b/src/backend/commands/vacuumparallel.c index de2cb9c0dba..078b7bd97d3 100644 --- a/src/backend/commands/vacuumparallel.c +++ b/src/backend/commands/vacuumparallel.c @@ -26,6 +26,8 @@ */ #include "postgres.h" +#include + #include "access/amapi.h" #include "access/table.h" #include "access/xact.h" @@ -33,6 +35,7 @@ #include "commands/vacuum.h" #include "optimizer/paths.h" #include "pgstat.h" +#include "postmaster/autovacuum.h" #include "storage/bufmgr.h" #include "tcop/tcopprot.h" #include "utils/lsyscache.h" @@ -64,6 +67,9 @@ typedef struct PVShared Oid relid; int elevel; + /* Leader's autovacuum flag, used for worker timing statistics. */ + bool is_autovacuum; + /* * Fields for both index vacuum and cleanup. * @@ -365,6 +371,7 @@ parallel_vacuum_init(Relation rel, Relation *indrels, int nindexes, shared = (PVShared *) shm_toc_allocate(pcxt->toc, est_shared_len); MemSet(shared, 0, est_shared_len); shared->relid = RelationGetRelid(rel); + shared->is_autovacuum = IsAutoVacuumWorkerProcess(); shared->elevel = elevel; shared->maintenance_work_mem_worker = (nindexes_mwm > 0) ? @@ -837,6 +844,8 @@ parallel_vacuum_process_one_index(ParallelVacuumState *pvs, Relation indrel, IndexBulkDeleteResult *istat_res; IndexVacuumInfo ivinfo; LVExtStatCounters *extVacCounters; + TimestampTz istarttime = GetCurrentTimestamp(); + double startdelaytime = VacuumDelayTime; /* * Update the pointer to the corresponding bulk-deletion result if someone @@ -886,6 +895,18 @@ parallel_vacuum_process_one_index(ParallelVacuumState *pvs, Relation indrel, pfree(extVacCounters); } + /* + * Accumulate this pass into the index's cumulative vacuum times. Use the + * leader's DSM flag to classify autovacuum: a parallel worker of an + * autovacuum leader is a regular background worker. + */ + pgstat_report_index_vacuum_time(indrel, + TimestampDifferenceMilliseconds(istarttime, + GetCurrentTimestamp()), + (PgStat_Counter) rint(VacuumDelayTime - + startdelaytime), + pvs->shared->is_autovacuum); + /* * Copy the index bulk-deletion result returned from ambulkdelete and * amvacuumcleanup to the DSM segment if it's the first cycle because they diff --git a/src/backend/utils/activity/pgstat_database.c b/src/backend/utils/activity/pgstat_database.c index 813aa359fa0..0f6b9f7f1c4 100644 --- a/src/backend/utils/activity/pgstat_database.c +++ b/src/backend/utils/activity/pgstat_database.c @@ -37,6 +37,7 @@ static int pgStatXactRollback = 0; static PgStat_Counter pgLastSessionReportTime = 0; + /* * Remove entry for the database being dropped. */ @@ -417,6 +418,10 @@ pgstat_database_flush_cb(PgStat_EntryRef *entry_ref, bool nowait) PGSTAT_ACCUM_DBCOUNT(blk_read_time); PGSTAT_ACCUM_DBCOUNT(blk_write_time); + PGSTAT_ACCUM_DBCOUNT(total_vacuum_time); + PGSTAT_ACCUM_DBCOUNT(total_autovacuum_time); + PGSTAT_ACCUM_DBCOUNT(total_vacuum_delay_time); + PGSTAT_ACCUM_DBCOUNT(total_autovacuum_delay_time); PGSTAT_ACCUM_DBCOUNT(sessions); PGSTAT_ACCUM_DBCOUNT(session_time); diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c index 0a47a18e638..ec67130c336 100644 --- a/src/backend/utils/activity/pgstat_relation.c +++ b/src/backend/utils/activity/pgstat_relation.c @@ -216,7 +216,7 @@ pgstat_drop_relation(Relation rel) void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, - TimestampTz starttime) + TimestampTz starttime, PgStat_Counter delaytime) { PgStat_EntryRef *entry_ref; PgStatShared_Relation *shtabentry; @@ -259,16 +259,39 @@ pgstat_report_vacuum(Oid tableoid, bool shared, tabentry->last_autovacuum_time = ts; tabentry->autovacuum_count++; tabentry->total_autovacuum_time += elapsedtime; + tabentry->total_autovacuum_delay_time += delaytime; } else { tabentry->last_vacuum_time = ts; tabentry->vacuum_count++; tabentry->total_vacuum_time += elapsedtime; + tabentry->total_vacuum_delay_time += delaytime; } pgstat_unlock_entry(entry_ref); + /* + * Accumulate the same times into the database-wide totals. Index + * processing happens inside the table's run, so per-index times reported + * via pgstat_report_index_vacuum_time() are not added here again. The + * database entry is stored in microseconds, as its other time counters. + */ + { + PgStat_StatDBEntry *dbentry = pgstat_prep_database_pending(dboid); + + if (IsAutoVacuumWorkerProcess()) + { + dbentry->total_autovacuum_time += elapsedtime * 1000; + dbentry->total_autovacuum_delay_time += delaytime * 1000; + } + else + { + dbentry->total_vacuum_time += elapsedtime * 1000; + dbentry->total_vacuum_delay_time += delaytime * 1000; + } + } + /* * Flush IO statistics now. pgstat_report_stat() will flush IO stats, * however this will not be called until after an entire autovacuum cycle @@ -278,6 +301,49 @@ pgstat_report_vacuum(Oid tableoid, bool shared, pgstat_flush_io(false); } +/* + * Report the time spent vacuuming an index. + * + * Vacuum may process an index several times: a bulkdelete pass per index + * scan cycle plus a final cleanup pass, possibly spread across parallel + * workers. Each pass adds its elapsed and delay time here, accumulating + * into the index's total_vacuum_time or total_autovacuum_time, mirroring + * the table-level counters. The caller says whether this is autovacuum: + * parallel workers of an autovacuum leader are regular background workers, + * so IsAutoVacuumWorkerProcess() cannot be relied upon here. + */ +void +pgstat_report_index_vacuum_time(Relation rel, PgStat_Counter elapsedtime, + PgStat_Counter delaytime, bool is_autovacuum) +{ + PgStat_EntryRef *entry_ref; + PgStatShared_Relation *shtabentry; + PgStat_StatTabEntry *tabentry; + Oid dboid = (rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId); + + if (!pgstat_track_counts) + return; + + /* block acquiring lock for the same reason as pgstat_report_autovac() */ + entry_ref = pgstat_get_entry_ref_locked(PGSTAT_KIND_RELATION, dboid, + RelationGetRelid(rel), false); + shtabentry = (PgStatShared_Relation *) entry_ref->shared_stats; + tabentry = &shtabentry->stats; + + if (is_autovacuum) + { + tabentry->total_autovacuum_time += elapsedtime; + tabentry->total_autovacuum_delay_time += delaytime; + } + else + { + tabentry->total_vacuum_time += elapsedtime; + tabentry->total_vacuum_delay_time += delaytime; + } + + pgstat_unlock_entry(entry_ref); +} + /* * Report that the table was just analyzed and flush IO statistics. * diff --git a/src/include/pgstat.h b/src/include/pgstat.h index e059ffe29a7..0a3c4959b6f 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -233,7 +233,7 @@ typedef struct PgStat_TableXactStatus * ------------------------------------------------------------ */ -#define PGSTAT_FILE_FORMAT_ID 0x01A5BCAE +#define PGSTAT_FILE_FORMAT_ID 0x01A5BCAF typedef struct PgStat_ArchiverStats { @@ -349,6 +349,17 @@ typedef struct PgStat_StatDBEntry PgStat_Counter sessions_fatal; PgStat_Counter sessions_killed; + /* + * Cumulative time vacuums spent processing tables of this database and + * sleeping in cost-based delay points, in microseconds (the delay parts + * advance only when track_cost_delay_timing is enabled). Times of index + * processing are included in the owning table's run. + */ + PgStat_Counter total_vacuum_time; + PgStat_Counter total_autovacuum_time; + PgStat_Counter total_vacuum_delay_time; + PgStat_Counter total_autovacuum_delay_time; + TimestampTz stat_reset_timestamp; } PgStat_StatDBEntry; @@ -427,6 +438,14 @@ typedef struct PgStat_StatTabEntry PgStat_Counter total_autovacuum_time; PgStat_Counter total_analyze_time; PgStat_Counter total_autoanalyze_time; + + /* + * Time slept in cost-based vacuum delay points while vacuuming this + * relation, in milliseconds; nonzero only when track_cost_delay_timing + * is enabled. + */ + PgStat_Counter total_vacuum_delay_time; + PgStat_Counter total_autovacuum_delay_time; } PgStat_StatTabEntry; typedef struct PgStat_WalStats @@ -652,7 +671,11 @@ extern void pgstat_unlink_relation(Relation rel); extern void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, - TimestampTz starttime); + TimestampTz starttime, PgStat_Counter delaytime); +extern void pgstat_report_index_vacuum_time(Relation rel, + PgStat_Counter elapsedtime, + PgStat_Counter delaytime, + bool is_autovacuum); extern void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter, TimestampTz starttime); From 6c0b00ee9bbc771a71aa7838d61c5f213785f8a9 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Thu, 1 Oct 2026 16:21:14 +0300 Subject: [PATCH 07/20] Count vacuums that enter wraparound failsafe mode Accumulate relation and database failsafe counts for completed heap vacuums. Pass false for AO, which has no heap wraparound failsafe mode. Keep this counter distinct from scans made aggressive by the freeze age. Catalog getters, views and tests follow in the native SQL reporting commit. --- src/backend/access/heap/vacuumlazy.c | 3 ++- src/backend/commands/vacuum_ao.c | 3 ++- src/backend/utils/activity/pgstat_database.c | 1 + src/backend/utils/activity/pgstat_relation.c | 9 ++++++++- src/include/pgstat.h | 17 +++++++++++++++-- 5 files changed, 28 insertions(+), 5 deletions(-) diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c index 8c8a6b777c3..01486d08a67 100644 --- a/src/backend/access/heap/vacuumlazy.c +++ b/src/backend/access/heap/vacuumlazy.c @@ -795,7 +795,8 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, vacrel->recently_dead_tuples + vacrel->missed_dead_tuples, starttime, - (PgStat_Counter) rint(VacuumDelayTime - startdelaytime)); + (PgStat_Counter) rint(VacuumDelayTime - startdelaytime), + VacuumFailsafeActive); pgstat_progress_end_command(); if (instrument) diff --git a/src/backend/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c index be2f58b1f61..25cd3be46bd 100644 --- a/src/backend/commands/vacuum_ao.c +++ b/src/backend/commands/vacuum_ao.c @@ -322,7 +322,8 @@ ao_vacuum_rel_post_cleanup(Relation onerel, VacuumParams *params, BufferAccessSt reltuples, deadtuples, vacrelstats->starttime, - 0); /* AO delay time tracking is added in a later commit. */ + 0, /* AO delay time tracking is added in a later commit. */ + false); /* no failsafe mode for AO tables */ SIMPLE_FAULT_INJECTOR("vacuum_ao_post_cleanup_end"); diff --git a/src/backend/utils/activity/pgstat_database.c b/src/backend/utils/activity/pgstat_database.c index 0f6b9f7f1c4..2ec9d11f319 100644 --- a/src/backend/utils/activity/pgstat_database.c +++ b/src/backend/utils/activity/pgstat_database.c @@ -422,6 +422,7 @@ pgstat_database_flush_cb(PgStat_EntryRef *entry_ref, bool nowait) PGSTAT_ACCUM_DBCOUNT(total_autovacuum_time); PGSTAT_ACCUM_DBCOUNT(total_vacuum_delay_time); PGSTAT_ACCUM_DBCOUNT(total_autovacuum_delay_time); + PGSTAT_ACCUM_DBCOUNT(vacuum_failsafe_count); PGSTAT_ACCUM_DBCOUNT(sessions); PGSTAT_ACCUM_DBCOUNT(session_time); diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c index ec67130c336..3de04c945c8 100644 --- a/src/backend/utils/activity/pgstat_relation.c +++ b/src/backend/utils/activity/pgstat_relation.c @@ -216,7 +216,8 @@ pgstat_drop_relation(Relation rel) void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, - TimestampTz starttime, PgStat_Counter delaytime) + TimestampTz starttime, PgStat_Counter delaytime, + bool failsafe) { PgStat_EntryRef *entry_ref; PgStatShared_Relation *shtabentry; @@ -269,6 +270,9 @@ pgstat_report_vacuum(Oid tableoid, bool shared, tabentry->total_vacuum_delay_time += delaytime; } + if (failsafe) + tabentry->vacuum_failsafe_count++; + pgstat_unlock_entry(entry_ref); /* @@ -290,6 +294,9 @@ pgstat_report_vacuum(Oid tableoid, bool shared, dbentry->total_vacuum_time += elapsedtime * 1000; dbentry->total_vacuum_delay_time += delaytime * 1000; } + + if (failsafe) + dbentry->vacuum_failsafe_count++; } /* diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 0a3c4959b6f..92641e1a0b8 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -233,7 +233,7 @@ typedef struct PgStat_TableXactStatus * ------------------------------------------------------------ */ -#define PGSTAT_FILE_FORMAT_ID 0x01A5BCAF +#define PGSTAT_FILE_FORMAT_ID 0x01A5BCB0 typedef struct PgStat_ArchiverStats { @@ -360,6 +360,12 @@ typedef struct PgStat_StatDBEntry PgStat_Counter total_vacuum_delay_time; PgStat_Counter total_autovacuum_delay_time; + /* + * Number of vacuums in this database that entered the wraparound + * failsafe mode (see vacuum_failsafe_age). + */ + PgStat_Counter vacuum_failsafe_count; + TimestampTz stat_reset_timestamp; } PgStat_StatDBEntry; @@ -446,6 +452,12 @@ typedef struct PgStat_StatTabEntry */ PgStat_Counter total_vacuum_delay_time; PgStat_Counter total_autovacuum_delay_time; + + /* + * Number of vacuums of this relation that entered the wraparound + * failsafe mode (see vacuum_failsafe_age). + */ + PgStat_Counter vacuum_failsafe_count; } PgStat_StatTabEntry; typedef struct PgStat_WalStats @@ -671,7 +683,8 @@ extern void pgstat_unlink_relation(Relation rel); extern void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, - TimestampTz starttime, PgStat_Counter delaytime); + TimestampTz starttime, PgStat_Counter delaytime, + bool failsafe); extern void pgstat_report_index_vacuum_time(Relation rel, PgStat_Counter elapsedtime, PgStat_Counter delaytime, From 56a0b26b6d4da568f7ccd1ae78bb106bd3aeeca8 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Thu, 1 Oct 2026 16:21:15 +0300 Subject: [PATCH 08/20] Count vacuums interrupted by errors Count ERROR reports in the heap vacuum callback using local counters for database-local and shared relations. Transfer them to pending database statistics at transaction end. Test cancellation of a running vacuum. --- src/backend/access/heap/vacuumlazy.c | 4 ++ src/backend/utils/activity/pgstat_database.c | 55 ++++++++++++++++++++ src/include/pgstat.h | 6 ++- 3 files changed, 64 insertions(+), 1 deletion(-) diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c index 01486d08a67..86143f44c55 100644 --- a/src/backend/access/heap/vacuumlazy.c +++ b/src/backend/access/heap/vacuumlazy.c @@ -3677,6 +3677,10 @@ vacuum_error_callback(void *arg) { LVRelState *errinfo = arg; + /* Ignore non-error reports that also invoke this callback. */ + if (errinfo->rel != NULL && geterrlevel() == ERROR) + pgstat_count_vacuum_error(errinfo->rel->rd_rel->relisshared); + switch (errinfo->phase) { case VACUUM_ERRCB_PHASE_SCAN_HEAP: diff --git a/src/backend/utils/activity/pgstat_database.c b/src/backend/utils/activity/pgstat_database.c index 2ec9d11f319..a320a735c22 100644 --- a/src/backend/utils/activity/pgstat_database.c +++ b/src/backend/utils/activity/pgstat_database.c @@ -36,6 +36,12 @@ static int pgStatXactCommit = 0; static int pgStatXactRollback = 0; static PgStat_Counter pgLastSessionReportTime = 0; +/* + * Vacuums interrupted by an error, counted from the vacuum error callback + * and folded into the pending database entries at transaction end. + */ +static PgStat_Counter pgStatVacuumErrors = 0; +static PgStat_Counter pgStatSharedVacuumErrors = 0; /* @@ -246,6 +252,20 @@ pgstat_fetch_stat_dbentry(Oid dboid) pgstat_fetch_entry(PGSTAT_KIND_DATABASE, dboid, InvalidOid); } +/* + * Add the vacuum errors counted for a database to its pending entry, and + * reset the counter. + */ +static void +pgstat_fold_vacuum_errors(Oid dboid, PgStat_Counter *count) +{ + if (*count == 0) + return; + + pgstat_prep_database_pending(dboid)->vacuum_interrupt_count += *count; + *count = 0; +} + void AtEOXact_PgStat_Database(bool isCommit, bool parallel) { @@ -261,6 +281,15 @@ AtEOXact_PgStat_Database(bool isCommit, bool parallel) else pgStatXactRollback++; } + + /* + * Fold in the vacuums that pgstat_count_vacuum_error() saw failing. We + * are past LWLockReleaseAll() of the aborting transaction here, so it is + * safe to touch the pending entries, which the next pgstat_report_stat() + * flushes to shared memory as usual. + */ + pgstat_fold_vacuum_errors(MyDatabaseId, &pgStatVacuumErrors); + pgstat_fold_vacuum_errors(InvalidOid, &pgStatSharedVacuumErrors); } /* @@ -327,6 +356,31 @@ pgstat_should_report_connstat(void) return MyBackendType == B_BACKEND; } +/* + * Count a vacuum that was interrupted by an error. + * + * This is called from the vacuum error callback, that is from inside the + * error handler, so it must not do anything that could fail or block: the + * error may well have been raised by the locking code itself, possibly + * while holding an LWLock. Just bump a counter here; the counter reaches + * the pending database entry in AtEOXact_PgStat_Database(), once the + * transaction end has released the locks we might have been holding. + * + * Vacuums of shared relations are counted in the InvalidOid entry, matching + * how their other stats are accounted. + */ +void +pgstat_count_vacuum_error(bool shared) +{ + if (!pgstat_track_counts) + return; + + if (shared) + pgStatSharedVacuumErrors++; + else + pgStatVacuumErrors++; +} + /* * Find or create a local PgStat_StatDBEntry entry for dboid. */ @@ -423,6 +477,7 @@ pgstat_database_flush_cb(PgStat_EntryRef *entry_ref, bool nowait) PGSTAT_ACCUM_DBCOUNT(total_vacuum_delay_time); PGSTAT_ACCUM_DBCOUNT(total_autovacuum_delay_time); PGSTAT_ACCUM_DBCOUNT(vacuum_failsafe_count); + PGSTAT_ACCUM_DBCOUNT(vacuum_interrupt_count); PGSTAT_ACCUM_DBCOUNT(sessions); PGSTAT_ACCUM_DBCOUNT(session_time); diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 92641e1a0b8..4946e40707d 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -233,7 +233,7 @@ typedef struct PgStat_TableXactStatus * ------------------------------------------------------------ */ -#define PGSTAT_FILE_FORMAT_ID 0x01A5BCB0 +#define PGSTAT_FILE_FORMAT_ID 0x01A5BCB1 typedef struct PgStat_ArchiverStats { @@ -366,6 +366,9 @@ typedef struct PgStat_StatDBEntry */ PgStat_Counter vacuum_failsafe_count; + /* # of vacuums in this database interrupted by errors */ + PgStat_Counter vacuum_interrupt_count; + TimestampTz stat_reset_timestamp; } PgStat_StatDBEntry; @@ -689,6 +692,7 @@ extern void pgstat_report_index_vacuum_time(Relation rel, PgStat_Counter elapsedtime, PgStat_Counter delaytime, bool is_autovacuum); +extern void pgstat_count_vacuum_error(bool shared); extern void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, bool resetcounter, TimestampTz starttime); From e2a492f5aae78f1f01ee175bb63e735f2fa452ce Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Mon, 30 Mar 2026 09:07:24 +0300 Subject: [PATCH 09/20] Track table VM stability. Add visible_page_marks_cleared and frozen_page_marks_cleared counters to pg_stat_all_tables tracking the number of times the all-visible and all-frozen bits are cleared in the visibility map. These bits are cleared by backend processes during regular DML operations. Hence, the counters are placed in table statistic entry. A high visible_page_marks_cleared rate relative to DML volume indicates that modifications are scattered across previously-clean pages rather than concentrated on already-dirty ones, causing index-only scans to fall back to heap fetches. A high frozen_page_marks_cleared rate indicates that vacuum's freezing work is being frequently undone by concurrent DML. Authors: Alena Rybakina , Andrei Lepikhov , Andrei Zubkov Reviewed-by: Dilip Kumar , Masahiko Sawada , Ilia Evdokimov , Jian He , Kirill Reshke , Alexander Korotkov , Jim Nasby , Sami Imseih , Karina Litskevich , Andrey Borodin Backported-from: https://www.postgresql.org/message-id/attachment/205562/v45-0009-Track-table-VM-stability.patch Co-authored-by: Andrei Lepikhov Co-authored-by: Andrei Zubkov --- src/backend/access/heap/heapam.c | 16 +++---- src/backend/access/heap/vacuumlazy.c | 4 +- src/backend/access/heap/visibilitymap.c | 46 ++++++++++++++++++++ src/backend/utils/activity/pgstat_relation.c | 2 + src/include/access/visibilitymap.h | 2 + src/include/pgstat.h | 34 ++++++++++++++- 6 files changed, 93 insertions(+), 11 deletions(-) diff --git a/src/backend/access/heap/heapam.c b/src/backend/access/heap/heapam.c index 19c69270371..7fd1244ed66 100644 --- a/src/backend/access/heap/heapam.c +++ b/src/backend/access/heap/heapam.c @@ -1974,7 +1974,7 @@ heap_insert(Relation relation, HeapTuple tup, CommandId cid, { all_visible_cleared = true; PageClearAllVisible(BufferGetPage(buffer)); - visibilitymap_clear(relation, + visibilitymap_clear_rel(relation, ItemPointerGetBlockNumber(&(heaptup->t_self)), vmbuffer, VISIBILITYMAP_VALID_BITS); } @@ -2350,7 +2350,7 @@ heap_multi_insert(Relation relation, TupleTableSlot **slots, int ntuples, { all_visible_cleared = true; PageClearAllVisible(page); - visibilitymap_clear(relation, + visibilitymap_clear_rel(relation, BufferGetBlockNumber(buffer), vmbuffer, VISIBILITYMAP_VALID_BITS); } @@ -2935,7 +2935,7 @@ heap_delete(Relation relation, ItemPointer tid, { all_visible_cleared = true; PageClearAllVisible(page); - visibilitymap_clear(relation, BufferGetBlockNumber(buffer), + visibilitymap_clear_rel(relation, BufferGetBlockNumber(buffer), vmbuffer, VISIBILITYMAP_VALID_BITS); } @@ -3764,7 +3764,7 @@ heap_update(Relation relation, ItemPointer otid, HeapTuple newtup, * worthwhile. */ if (PageIsAllVisible(page) && - visibilitymap_clear(relation, block, vmbuffer, + visibilitymap_clear_rel(relation, block, vmbuffer, VISIBILITYMAP_ALL_FROZEN)) cleared_all_frozen = true; @@ -3998,14 +3998,14 @@ heap_update(Relation relation, ItemPointer otid, HeapTuple newtup, { all_visible_cleared = true; PageClearAllVisible(BufferGetPage(buffer)); - visibilitymap_clear(relation, BufferGetBlockNumber(buffer), + visibilitymap_clear_rel(relation, BufferGetBlockNumber(buffer), vmbuffer, VISIBILITYMAP_VALID_BITS); } if (newbuf != buffer && PageIsAllVisible(BufferGetPage(newbuf))) { all_visible_cleared_new = true; PageClearAllVisible(BufferGetPage(newbuf)); - visibilitymap_clear(relation, BufferGetBlockNumber(newbuf), + visibilitymap_clear_rel(relation, BufferGetBlockNumber(newbuf), vmbuffer_new, VISIBILITYMAP_VALID_BITS); } @@ -5095,7 +5095,7 @@ heap_lock_tuple(Relation relation, HeapTuple tuple, /* Clear only the all-frozen bit on visibility map if needed */ if (PageIsAllVisible(page) && - visibilitymap_clear(relation, block, vmbuffer, + visibilitymap_clear_rel(relation, block, vmbuffer, VISIBILITYMAP_ALL_FROZEN)) cleared_all_frozen = true; @@ -5852,7 +5852,7 @@ heap_lock_updated_tuple_rec(Relation rel, ItemPointer tid, TransactionId xid, &new_xmax, &new_infomask, &new_infomask2); if (PageIsAllVisible(BufferGetPage(buf)) && - visibilitymap_clear(rel, block, vmbuffer, + visibilitymap_clear_rel(rel, block, vmbuffer, VISIBILITYMAP_ALL_FROZEN)) cleared_all_frozen = true; diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c index 86143f44c55..c2eac3462f5 100644 --- a/src/backend/access/heap/vacuumlazy.c +++ b/src/backend/access/heap/vacuumlazy.c @@ -1329,7 +1329,7 @@ lazy_scan_heap(LVRelState *vacrel) { elog(WARNING, "page is not marked all-visible but visibility map bit is set in relation \"%s\" page %u", vacrel->relname, blkno); - visibilitymap_clear(vacrel->rel, blkno, vmbuffer, + visibilitymap_clear_rel(vacrel->rel, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS); } @@ -1354,7 +1354,7 @@ lazy_scan_heap(LVRelState *vacrel) vacrel->relname, blkno); PageClearAllVisible(page); MarkBufferDirty(buf); - visibilitymap_clear(vacrel->rel, blkno, vmbuffer, + visibilitymap_clear_rel(vacrel->rel, blkno, vmbuffer, VISIBILITYMAP_VALID_BITS); } diff --git a/src/backend/access/heap/visibilitymap.c b/src/backend/access/heap/visibilitymap.c index 2e18cd88bcf..562c7fdc10f 100644 --- a/src/backend/access/heap/visibilitymap.c +++ b/src/backend/access/heap/visibilitymap.c @@ -12,6 +12,8 @@ * * INTERFACE ROUTINES * visibilitymap_clear - clear bits for one page in the visibility map + * visibilitymap_clear_rel - clear bits for an open relation, counting the + * clears in its statistics * visibilitymap_pin - pin a map page for setting a bit * visibilitymap_pin_ok - check whether correct map page is already pinned * visibilitymap_set - set a bit in a previously pinned page @@ -91,6 +93,7 @@ #include "access/xloginsert.h" #include "access/xlogutils.h" #include "miscadmin.h" +#include "pgstat.h" #include "port/pg_bitutils.h" #include "storage/bufmgr.h" #include "storage/lmgr.h" @@ -125,6 +128,8 @@ * bit pair */ /* prototypes for internal routines */ +static bool vm_do_clear(Relation rel, BlockNumber heapBlk, Buffer vmbuf, + uint8 flags, bool count_stats); static Buffer vm_readbuf(Relation rel, BlockNumber blkno, bool extend); static Buffer vm_extend(Relation rel, BlockNumber vm_nblocks); @@ -135,9 +140,38 @@ static Buffer vm_extend(Relation rel, BlockNumber vm_nblocks); * You must pass a buffer containing the correct map page to this function. * Call visibilitymap_pin first to pin the right one. This function doesn't do * any I/O. Returns true if any bits have been cleared and false otherwise. + * + * This variant is for callers such as recovery, which use a fake relcache + * entry and cannot count the clears in the relation's statistics; callers + * holding an open relation should use visibilitymap_clear_rel() instead. */ bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer vmbuf, uint8 flags) +{ + return vm_do_clear(rel, heapBlk, vmbuf, flags, false); +} + +/* + * visibilitymap_clear_rel - visibilitymap_clear() for an open relation + * + * Same as visibilitymap_clear(), but additionally counts the cleared + * all-visible and all-frozen marks in the relation's statistics, which + * makes the stability of its visibility map observable. + */ +bool +visibilitymap_clear_rel(Relation rel, BlockNumber heapBlk, Buffer vmbuf, + uint8 flags) +{ + return vm_do_clear(rel, heapBlk, vmbuf, flags, true); +} + +/* + * Workhorse of visibilitymap_clear() and visibilitymap_clear_rel(). + * count_stats is false when the caller has no real relcache entry at hand. + */ +static bool +vm_do_clear(Relation rel, BlockNumber heapBlk, Buffer vmbuf, uint8 flags, + bool count_stats) { BlockNumber mapBlock = HEAPBLK_TO_MAPBLOCK(heapBlk); int mapByte = HEAPBLK_TO_MAPBYTE(heapBlk); @@ -162,6 +196,18 @@ visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer vmbuf, uint8 flags if (map[mapByte] & mask) { + /* + * Track how often all-visible or all-frozen bits are cleared in the + * visibility map. + */ + if (count_stats) + { + if (map[mapByte] & ((flags & VISIBILITYMAP_ALL_VISIBLE) << mapOffset)) + pgstat_count_visible_page_marks_cleared(rel); + if (map[mapByte] & ((flags & VISIBILITYMAP_ALL_FROZEN) << mapOffset)) + pgstat_count_frozen_page_marks_cleared(rel); + } + map[mapByte] &= ~mask; MarkBufferDirty(vmbuf); diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c index 3de04c945c8..95423272731 100644 --- a/src/backend/utils/activity/pgstat_relation.c +++ b/src/backend/utils/activity/pgstat_relation.c @@ -920,6 +920,8 @@ pgstat_relation_flush_cb(PgStat_EntryRef *entry_ref, bool nowait) tabentry->ins_since_vacuum += lstats->counts.tuples_inserted; tabentry->blocks_fetched += lstats->counts.blocks_fetched; tabentry->blocks_hit += lstats->counts.blocks_hit; + tabentry->visible_page_marks_cleared += lstats->counts.visible_page_marks_cleared; + tabentry->frozen_page_marks_cleared += lstats->counts.frozen_page_marks_cleared; /* Clamp live_tuples in case of negative delta_live_tuples */ tabentry->live_tuples = Max(tabentry->live_tuples, 0); diff --git a/src/include/access/visibilitymap.h b/src/include/access/visibilitymap.h index daaa01a2578..6af0fd5304d 100644 --- a/src/include/access/visibilitymap.h +++ b/src/include/access/visibilitymap.h @@ -26,6 +26,8 @@ #define VM_ALL_FROZEN(r, b, v) \ ((visibilitymap_get_status((r), (b), (v)) & VISIBILITYMAP_ALL_FROZEN) != 0) +extern bool visibilitymap_clear_rel(Relation rel, BlockNumber heapBlk, + Buffer vmbuf, uint8 flags); extern bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer vmbuf, uint8 flags); extern void visibilitymap_pin(Relation rel, BlockNumber heapBlk, diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 4946e40707d..e93364c0c29 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -175,6 +175,14 @@ typedef struct PgStat_TableCounts PgStat_Counter blocks_fetched; PgStat_Counter blocks_hit; + + /* + * Revocations of all-visible and all-frozen marks in the visibility map. + * The bits are cleared by the page modification itself, so these count + * whether or not the transaction commits. + */ + PgStat_Counter visible_page_marks_cleared; + PgStat_Counter frozen_page_marks_cleared; } PgStat_TableCounts; /* ---------- @@ -233,7 +241,7 @@ typedef struct PgStat_TableXactStatus * ------------------------------------------------------------ */ -#define PGSTAT_FILE_FORMAT_ID 0x01A5BCB1 +#define PGSTAT_FILE_FORMAT_ID 0x01A5BCB2 typedef struct PgStat_ArchiverStats { @@ -433,6 +441,8 @@ typedef struct PgStat_StatTabEntry PgStat_Counter blocks_fetched; PgStat_Counter blocks_hit; + PgStat_Counter visible_page_marks_cleared; + PgStat_Counter frozen_page_marks_cleared; TimestampTz last_vacuum_time; /* user initiated vacuum */ PgStat_Counter vacuum_count; @@ -744,6 +754,28 @@ extern void pgstat_report_analyze(Relation rel, (rel)->pgstat_info->counts.blocks_hit++; \ } while (0) +/* + * Count revocations of all-visible and all-frozen marks in the visibility + * map. Only tables have a visibility map, so these always work on the + * table's pending counters. These macros can run inside a critical section: + * never create a pending entry here. Reading the heap buffer normally + * associates the entry before the caller enters the critical section. + */ +#define pgstat_count_visible_page_marks_cleared(rel) \ + do { \ + if ((rel)->pgstat_info != NULL) \ + { \ + (rel)->pgstat_info->counts.visible_page_marks_cleared++; \ + } \ + } while (0) +#define pgstat_count_frozen_page_marks_cleared(rel) \ + do { \ + if ((rel)->pgstat_info != NULL) \ + { \ + (rel)->pgstat_info->counts.frozen_page_marks_cleared++; \ + } \ + } while (0) + extern void pgstat_count_heap_insert(Relation rel, PgStat_Counter n); extern void pgstat_count_heap_update(Relation rel, bool hot, bool newpage); extern void pgstat_count_heap_delete(Relation rel); From 50a4ff832d1ba659dd973b8eab1a5394f4cfe8aa Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Thu, 1 Oct 2026 16:21:15 +0300 Subject: [PATCH 10/20] Report core vacuum timing for append-optimized tables Connect AO index-pass timing measurements to cumulative statistics and report interrupted vacuums. Add cumulative delay reporting for AO tables. Failsafe and visibility-map counters remain inapplicable to AO. The cluster isolation test is included later with its gp_stat_vacuum dependency. Active-phase elapsed reporting is connected in a later commit. --- src/backend/commands/vacuum_ao.c | 53 +++++++++++++++++----- src/include/access/appendonly_compaction.h | 1 + 2 files changed, 42 insertions(+), 12 deletions(-) diff --git a/src/backend/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c index 25cd3be46bd..dea9d403609 100644 --- a/src/backend/commands/vacuum_ao.c +++ b/src/backend/commands/vacuum_ao.c @@ -171,8 +171,9 @@ static void ao_accum_resources(PgStat_CommonCounts *dst, static void ao_measure_index_resources(Relation indrel, LVExtStatCounters *counters, AOVacuumRelStats *vacrelstats, bool verbose); -static void ao_measure_index_vacuum_time(Relation indrel, TimestampTz starttime, +static void ao_report_index_vacuum_time(Relation indrel, TimestampTz starttime, double startdelaytime); +static void ao_vacuum_error_callback(void *arg); static void ao_vacuum_rel_pre_cleanup(Relation onerel, VacuumParams *params, BufferAccessStrategy bstrategy, AOVacuumRelStats *vacrelstats) @@ -322,7 +323,8 @@ ao_vacuum_rel_post_cleanup(Relation onerel, VacuumParams *params, BufferAccessSt reltuples, deadtuples, vacrelstats->starttime, - 0, /* AO delay time tracking is added in a later commit. */ + (PgStat_Counter) rint(VacuumDelayTime - + vacrelstats->startdelaytime), false); /* no failsafe mode for AO tables */ @@ -435,6 +437,7 @@ init_vacrelstats(bool instrument) if (instrument) vacrelstats->extstats = palloc0(sizeof(AOVacuumExtStats)); vacrelstats->starttime = GetCurrentTimestamp(); + vacrelstats->startdelaytime = VacuumDelayTime; MemoryContextSwitchTo(old_context); return vacrelstats; @@ -452,6 +455,7 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy LVExtStatCounters *extcounters; bool verbose = (params->options & VACOPT_VERBOSE) != 0; PgStat_CommonCounts index_start = {0}; + ErrorContextCallback errcallback; instr_time phase_start; instr_time phase_end; double phase_start_delay; @@ -500,6 +504,12 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy if (vacrelstats->extstats != NULL) index_start = vacrelstats->extstats->indexes; + /* Count the vacuums of the relation that an error interrupts */ + errcallback.callback = ao_vacuum_error_callback; + errcallback.arg = rel; + errcallback.previous = error_context_stack; + error_context_stack = &errcallback; + INSTR_TIME_SET_CURRENT(phase_start); phase_start_delay = VacuumDelayTime; @@ -555,6 +565,8 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy cleanup_vacrelstats(&vacrelstats); } + error_context_stack = errcallback.previous; + if (extcounters != NULL) pfree(extcounters); } @@ -668,22 +680,39 @@ ao_measure_index_resources(Relation indrel, LVExtStatCounters *counters, pfree(counters); } +/* + * Error context callback of an append-optimized vacuum phase. + * + * Like vacuum_error_callback() of the heap, count a vacuum interrupted by an + * actual ERROR, not by a lower-severity report that merely carries this + * context, in vacuum_interrupt_count of the database. We are inside the + * error handler, so pgstat_count_vacuum_error() only bumps a counter. The + * callback adds no context line: the phases report their own progress. + */ +static void +ao_vacuum_error_callback(void *arg) +{ + Relation rel = (Relation) arg; + + if (geterrlevel() == ERROR) + pgstat_count_vacuum_error(rel->rd_rel->relisshared); +} + /* * Accumulate one vacuum pass over an index of an append-optimized table * into the index's cumulative vacuum and delay times, as the heap does in * lazy_vacuum_one_index() and lazy_cleanup_one_index(). */ static void -ao_measure_index_vacuum_time(Relation indrel, TimestampTz starttime, +ao_report_index_vacuum_time(Relation indrel, TimestampTz starttime, double startdelaytime) { - PgStat_Counter elapsedtime = - TimestampDifferenceMilliseconds(starttime, GetCurrentTimestamp()); - PgStat_Counter delaytime = (PgStat_Counter) rint(VacuumDelayTime - startdelaytime); - - /* Backend-local measurements; cumulative reporting follows separately. */ - (void) elapsedtime; - (void) delaytime; + pgstat_report_index_vacuum_time(indrel, + TimestampDifferenceMilliseconds(starttime, + GetCurrentTimestamp()), + (PgStat_Counter) rint(VacuumDelayTime - + startdelaytime), + IsAutoVacuumWorkerProcess()); } /* @@ -806,7 +835,7 @@ vacuum_appendonly_indexes(Relation aoRelation, int options, Bitmapset *dead_segs ao_measure_index_resources(Irel[i], extcounters, vacrelstats, elevel == INFO && Gp_role != GP_ROLE_DISPATCH); - ao_measure_index_vacuum_time(Irel[i], istarttime, startdelaytime); + ao_report_index_vacuum_time(Irel[i], istarttime, startdelaytime); } } else @@ -829,7 +858,7 @@ vacuum_appendonly_indexes(Relation aoRelation, int options, Bitmapset *dead_segs ao_measure_index_resources(Irel[i], extcounters, vacrelstats, elevel == INFO && Gp_role != GP_ROLE_DISPATCH); - ao_measure_index_vacuum_time(Irel[i], istarttime, startdelaytime); + ao_report_index_vacuum_time(Irel[i], istarttime, startdelaytime); } } } diff --git a/src/include/access/appendonly_compaction.h b/src/include/access/appendonly_compaction.h index 5fd3b989cab..71ad67540e3 100644 --- a/src/include/access/appendonly_compaction.h +++ b/src/include/access/appendonly_compaction.h @@ -42,6 +42,7 @@ typedef struct AOVacuumRelStats int num_index_vacuumed; /* current # of indexes been vacuumed */ /* Legacy timing-report baseline, retained until elapsed-time reporting. */ TimestampTz starttime; + double startdelaytime; /* Active phase durations and delays in milliseconds, excluding phase gaps. */ double vacuum_time; double delay_time; From 826213f499e70c2b98e1dba0c022e0d392bb1c16 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Thu, 8 Oct 2026 00:00:00 +0300 Subject: [PATCH 11/20] Document cost-based VACUUM delay timing Describe track_cost_delay_timing alongside the instrumentation it enables. Give the accumulated instrumentation fields their own statistics-file format identifier independent of the pluggable-statistics series. --- doc/src/sgml/config.sgml | 31 +++++++++++++++++++++++++++++++ src/include/pgstat.h | 2 +- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/doc/src/sgml/config.sgml b/doc/src/sgml/config.sgml index 93898dc9170..471c9f06744 100644 --- a/doc/src/sgml/config.sgml +++ b/doc/src/sgml/config.sgml @@ -8155,6 +8155,37 @@ COPY postgres_log FROM '/full/path/to/logfile.csv' WITH csv; + + track_cost_delay_timing (boolean) + + track_cost_delay_timing configuration parameter + + + + + Enables timing of cost-based vacuum delay (see + ). This parameter + is off by default, as it will repeatedly query the operating system for + the current time, which may cause significant overhead on some + platforms. You can use the tool to + measure the overhead of timing on your system. Cost-based vacuum delay + timing information is displayed in + pg_stat_progress_vacuum + and + pg_stat_progress_analyze. + Only superusers and users with the appropriate SET + privilege can change this setting. + + + In Cloudberry this setting is local to each instance. A session + SET on the coordinator is not propagated to segments. + To measure segment delays, configure the setting on those instances, + for example with gpconfig -c track_cost_delay_timing -v on + followed by gpstop -u. + + + + track_io_timing (boolean) diff --git a/src/include/pgstat.h b/src/include/pgstat.h index e93364c0c29..0c37d9f8017 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -241,7 +241,7 @@ typedef struct PgStat_TableXactStatus * ------------------------------------------------------------ */ -#define PGSTAT_FILE_FORMAT_ID 0x01A5BCB2 +#define PGSTAT_FILE_FORMAT_ID 0x01A5BCB4 typedef struct PgStat_ArchiverStats { From 57e954931c17e9fb1f50ac9db68343010d84409d Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Wed, 7 Oct 2026 16:52:12 +0300 Subject: [PATCH 12/20] Report AO active-phase time to cumulative statistics Publish elapsed and cost-delay time after each successful AO phase, preserving work if the next phase runs in a replacement QE. Exclude gaps between phases and retain consumed time after a later rollback. Only post-cleanup updates tuple estimates and the completed-vacuum count. Remove obsolete cross-phase timing state. SQL exposure, documentation and tests follow separately. --- src/backend/commands/vacuum_ao.c | 29 +++++---- src/backend/utils/activity/pgstat_relation.c | 64 ++++++++++++++------ src/include/access/appendonly_compaction.h | 6 -- src/include/pgstat.h | 4 ++ 4 files changed, 63 insertions(+), 40 deletions(-) diff --git a/src/backend/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c index dea9d403609..bfd23a61e3a 100644 --- a/src/backend/commands/vacuum_ao.c +++ b/src/backend/commands/vacuum_ao.c @@ -317,17 +317,6 @@ ao_vacuum_rel_post_cleanup(Relation onerel, VacuumParams *params, BufferAccessSt vacrelstats->live_tuples = reltuples; vacrelstats->dead_tuples = deadtuples; - /* report results to the stats collector, too */ - pgstat_report_vacuum(RelationGetRelid(onerel), - onerel->rd_rel->relisshared, - reltuples, - deadtuples, - vacrelstats->starttime, - (PgStat_Counter) rint(VacuumDelayTime - - vacrelstats->startdelaytime), - false); /* no failsafe mode for AO tables */ - - SIMPLE_FAULT_INJECTOR("vacuum_ao_post_cleanup_end"); } @@ -436,8 +425,6 @@ init_vacrelstats(bool instrument) vacrelstats = (AOVacuumRelStats *) palloc0(sizeof(AOVacuumRelStats)); if (instrument) vacrelstats->extstats = palloc0(sizeof(AOVacuumExtStats)); - vacrelstats->starttime = GetCurrentTimestamp(); - vacrelstats->startdelaytime = VacuumDelayTime; MemoryContextSwitchTo(old_context); return vacrelstats; @@ -555,8 +542,20 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy { INSTR_TIME_SET_CURRENT(phase_end); INSTR_TIME_SUBTRACT(phase_end, phase_start); - vacrelstats->vacuum_time += INSTR_TIME_GET_MILLISEC(phase_end); - vacrelstats->delay_time += VacuumDelayTime - phase_start_delay; + + /* + * Publish each phase before its QE can be replaced. Elapsed and + * delay times describe resources consumed, even if compaction's + * distributed transaction later rolls back. Only post-cleanup + * reports a completed vacuum and the final tuple estimates. + */ + pgstat_report_vacuum_elapsed(RelationGetRelid(rel), + rel->rd_rel->relisshared, + vacrelstats->live_tuples, vacrelstats->dead_tuples, + (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(phase_end)), + (PgStat_Counter) rint(VacuumDelayTime - phase_start_delay), + false, /* AO has no failsafe mode. */ + ao_vacuum_phase == VACOPT_AO_POST_CLEANUP_PHASE); } if (ao_vacuum_phase == VACOPT_AO_POST_CLEANUP_PHASE) diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c index 95423272731..b412feb71af 100644 --- a/src/backend/utils/activity/pgstat_relation.c +++ b/src/backend/utils/activity/pgstat_relation.c @@ -218,20 +218,36 @@ pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, TimestampTz starttime, PgStat_Counter delaytime, bool failsafe) +{ + pgstat_report_vacuum_elapsed(tableoid, shared, livetuples, deadtuples, + TimestampDifferenceMilliseconds(starttime, + GetCurrentTimestamp()), + delaytime, failsafe, true); +} + +/* + * Report elapsed time for a completed vacuum or one completed AO phase (ms). + * Only the final phase updates tuple estimates and the completed-vacuum count. + * Times measure work already performed, so they are intentionally not rolled + * back if a distributed transaction subsequently aborts. + */ +void +pgstat_report_vacuum_elapsed(Oid tableoid, bool shared, + PgStat_Counter livetuples, PgStat_Counter deadtuples, + PgStat_Counter elapsedtime, PgStat_Counter delaytime, + bool failsafe, bool is_complete) { PgStat_EntryRef *entry_ref; PgStatShared_Relation *shtabentry; PgStat_StatTabEntry *tabentry; Oid dboid = (shared ? InvalidOid : MyDatabaseId); TimestampTz ts; - PgStat_Counter elapsedtime; if (!pgstat_track_counts) return; /* Store the data in the table's hash table entry. */ ts = GetCurrentTimestamp(); - elapsedtime = TimestampDifferenceMilliseconds(starttime, ts); /* block acquiring lock for the same reason as pgstat_report_autovac() */ entry_ref = pgstat_get_entry_ref_locked(PGSTAT_KIND_RELATION, @@ -240,32 +256,42 @@ pgstat_report_vacuum(Oid tableoid, bool shared, shtabentry = (PgStatShared_Relation *) entry_ref->shared_stats; tabentry = &shtabentry->stats; - tabentry->live_tuples = livetuples; - tabentry->dead_tuples = deadtuples; + if (is_complete) + { + tabentry->live_tuples = livetuples; + tabentry->dead_tuples = deadtuples; - /* - * It is quite possible that a non-aggressive VACUUM ended up skipping - * various pages, however, we'll zero the insert counter here regardless. - * It's currently used only to track when we need to perform an "insert" - * autovacuum, which are mainly intended to freeze newly inserted tuples. - * Zeroing this may just mean we'll not try to vacuum the table again - * until enough tuples have been inserted to trigger another insert - * autovacuum. An anti-wraparound autovacuum will catch any persistent - * stragglers. - */ - tabentry->ins_since_vacuum = 0; + /* + * It is quite possible that a non-aggressive VACUUM ended up skipping + * various pages, however, we'll zero the insert counter here regardless. + * It's currently used only to track when we need to perform an "insert" + * autovacuum, which are mainly intended to freeze newly inserted tuples. + * Zeroing this may just mean we'll not try to vacuum the table again + * until enough tuples have been inserted to trigger another insert + * autovacuum. An anti-wraparound autovacuum will catch any persistent + * stragglers. For AO, wait until the post-cleanup phase completes. + */ + tabentry->ins_since_vacuum = 0; + + if (IsAutoVacuumWorkerProcess()) + { + tabentry->last_autovacuum_time = ts; + tabentry->autovacuum_count++; + } + else + { + tabentry->last_vacuum_time = ts; + tabentry->vacuum_count++; + } + } if (IsAutoVacuumWorkerProcess()) { - tabentry->last_autovacuum_time = ts; - tabentry->autovacuum_count++; tabentry->total_autovacuum_time += elapsedtime; tabentry->total_autovacuum_delay_time += delaytime; } else { - tabentry->last_vacuum_time = ts; - tabentry->vacuum_count++; tabentry->total_vacuum_time += elapsedtime; tabentry->total_vacuum_delay_time += delaytime; } diff --git a/src/include/access/appendonly_compaction.h b/src/include/access/appendonly_compaction.h index 71ad67540e3..52e8bd04a74 100644 --- a/src/include/access/appendonly_compaction.h +++ b/src/include/access/appendonly_compaction.h @@ -40,12 +40,6 @@ typedef struct AOVacuumRelStats int64 nbytes_truncated; /* current # of bytes truncated from segment file */ int64 num_dead_tuples; /* current # of dead tuples */ int num_index_vacuumed; /* current # of indexes been vacuumed */ - /* Legacy timing-report baseline, retained until elapsed-time reporting. */ - TimestampTz starttime; - double startdelaytime; - /* Active phase durations and delays in milliseconds, excluding phase gaps. */ - double vacuum_time; - double delay_time; int64 live_tuples; int64 dead_tuples; diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 0c37d9f8017..528ded52928 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -694,6 +694,10 @@ extern void pgstat_init_relation(Relation rel); extern void pgstat_assoc_relation(Relation rel); extern void pgstat_unlink_relation(Relation rel); +extern void pgstat_report_vacuum_elapsed(Oid tableoid, bool shared, + PgStat_Counter livetuples, PgStat_Counter deadtuples, + PgStat_Counter elapsedtime, PgStat_Counter delaytime, + bool failsafe, bool is_complete); extern void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, TimestampTz starttime, PgStat_Counter delaytime, From 84ced56e8f7a0e45052479a1c9d312b6e9db06e3 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Thu, 8 Oct 2026 00:00:00 +0300 Subject: [PATCH 13/20] Expose maintenance timing and visibility-map statistics in catalogs Add native SQL getters and local/cluster views for maintenance elapsed and cost-delay time, failsafe runs, interrupted vacuums and cleared VM bits. Use coordinator ANALYZE times alongside coordinator counts, sum instance-level events, and expose worker delays in progress summaries. Document per-phase AO timing and add isolation coverage for auto-analyze, phase rollback, QE replacement and progress delays. Run the native maintenance TAP tests in the ic-tap CI job. --- .github/workflows/build-cloudberry.yml | 1 + doc/src/sgml/monitoring.sgml | 345 ++++++++++++++++++ src/backend/catalog/system_views.sql | 43 ++- src/backend/catalog/system_views_gp.in | 1 + .../catalog/system_views_gp_summary.sql | 63 +++- src/backend/utils/adt/pgstatfuncs.c | 61 ++++ src/include/catalog/catversion.h | 2 +- src/include/catalog/pg_proc.dat | 64 ++++ .../expected/vacuum-extending-freeze.out | 128 +++++++ src/test/isolation/isolation_schedule | 1 + .../specs/vacuum-extending-freeze.spec | 108 ++++++ .../expected/vacuum_analyze_stats.out | 99 +++++ .../expected/vacuum_ao_phase_timing.out | 87 +++++ .../isolation2/expected/vacuum_ao_stats.out | 147 ++++++++ .../expected/vacuum_progress_column.out | 6 + .../expected/vacuum_progress_delay.out | 102 ++++++ .../expected/vacuum_progress_row.out | 12 + src/test/isolation2/isolation2_schedule | 4 + .../isolation2/sql/vacuum_analyze_stats.sql | 73 ++++ .../isolation2/sql/vacuum_ao_phase_timing.sql | 55 +++ src/test/isolation2/sql/vacuum_ao_stats.sql | 93 +++++ .../isolation2/sql/vacuum_progress_column.sql | 3 + .../isolation2/sql/vacuum_progress_delay.sql | 67 ++++ .../isolation2/sql/vacuum_progress_row.sql | 6 + src/test/modules/test_misc/Makefile | 5 + src/test/modules/test_misc/meson.build | 3 + .../test_misc/t/016_index_vacuum_time.pl | 80 ++++ .../test_misc/t/017_vacuum_failsafe.pl | 71 ++++ .../test_misc/t/018_vacuum_interrupts.pl | 71 ++++ src/test/regress/expected/rules.out | 54 ++- src/test/regress/expected/vacuum_stats.out | 2 +- src/test/regress/sql/vacuum_stats.sql | 3 +- 32 files changed, 1840 insertions(+), 20 deletions(-) create mode 100644 src/test/isolation/expected/vacuum-extending-freeze.out create mode 100644 src/test/isolation/specs/vacuum-extending-freeze.spec create mode 100644 src/test/isolation2/expected/vacuum_analyze_stats.out create mode 100644 src/test/isolation2/expected/vacuum_ao_phase_timing.out create mode 100644 src/test/isolation2/expected/vacuum_ao_stats.out create mode 100644 src/test/isolation2/expected/vacuum_progress_delay.out create mode 100644 src/test/isolation2/sql/vacuum_analyze_stats.sql create mode 100644 src/test/isolation2/sql/vacuum_ao_phase_timing.sql create mode 100644 src/test/isolation2/sql/vacuum_ao_stats.sql create mode 100644 src/test/isolation2/sql/vacuum_progress_delay.sql create mode 100644 src/test/modules/test_misc/t/016_index_vacuum_time.pl create mode 100644 src/test/modules/test_misc/t/017_vacuum_failsafe.pl create mode 100644 src/test/modules/test_misc/t/018_vacuum_interrupts.pl diff --git a/.github/workflows/build-cloudberry.yml b/.github/workflows/build-cloudberry.yml index 805d3c541d6..733c3c09bb2 100644 --- a/.github/workflows/build-cloudberry.yml +++ b/.github/workflows/build-cloudberry.yml @@ -405,6 +405,7 @@ jobs: "src/bin/scripts:installcheck", "src/interfaces/libpq:installcheck", "src/test/postmaster:installcheck", + "src/test/modules/test_misc:installcheck-vacuum", "src/test/modules/ssl_passphrase_callback:install installcheck", "src/test/modules/test_custom_rmgrs:install installcheck", "src/test/modules/test_escape:all installcheck", diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml index f9ceead292f..ba1d71cd680 100644 --- a/doc/src/sgml/monitoring.sgml +++ b/doc/src/sgml/monitoring.sgml @@ -459,6 +459,12 @@ postgres 27093 0.0 0.0 30096 2752 ? Ss 11:34 0:00 postgres: ser + + pg_stat_vacuum + One row per database, plus one for shared objects, showing cumulative + vacuum statistics. See . + + pg_stat_database_conflictspg_stat_database_conflicts @@ -4697,6 +4703,155 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i + + <structname>pg_stat_vacuum</structname> + pg_stat_vacuum + + The pg_stat_vacuum view contains one row for each + database, plus one for shared objects, showing cumulative vacuum statistics + on the current instance. The current database's counters are reset + together with its other statistics by pg_stat_reset(). + + + In Cloudberry, gp_stat_vacuum shows these columns + for every instance, with gp_segment_id identifying + the instance. gp_stat_vacuum_summary sums the times + and the failsafe and interrupt counts across instances, and takes the latest + reset time for each database. These counts represent instance-level events: + one command can contribute more than one event if it affects several + instances. They are not counts of distinct distributed commands. + + + Append-optimized vacuum publishes elapsed and delay times after each phase + returns successfully. This preserves time already reported if a different + worker runs the next phase, and excludes gaps between phases. The times + describe resources consumed: a later transaction rollback or failure of a + subsequent phase does not undo them. A phase interrupted by an error before + returning is not timed. The completed-vacuum count and tuple estimates are + updated only after post-cleanup. The same rules apply to table-level times. + + + In gp_stat_all_tables_summary, manual and automatic + analyze times come from the coordinator, matching their counts and including + the time spent waiting for segment sampling. Segment workers classify their + analyze work as manual even when the coordinator starts an auto-analyze. + Table failsafe counts in the summary are sums of instance-level events. + + + <structname>pg_stat_vacuum</structname> View + + + + + Column Type + + + Description + + + + + + + datid oid + + + OID of this database, or 0 for objects belonging to a shared + relation + + + + + + datname name + + + Name of this database, or NULL for shared + objects. + + + + + + total_vacuum_time double precision + + + Total time manually invoked vacuums spent processing tables of this + database, in milliseconds (index processing is included in the owning + table's run) + + + + + + total_autovacuum_time double precision + + + Total time the autovacuum daemon spent processing tables of this + database, in milliseconds + + + + + + total_vacuum_delay_time double precision + + + Total time manually invoked vacuums of this database spent sleeping in + cost-based delay points, in milliseconds (counted only when + is enabled) + + + + + + total_autovacuum_delay_time double precision + + + Total time autovacuums of this database spent sleeping in cost-based + delay points, in milliseconds (counted only when + is enabled) + + + + + + vacuum_failsafe_count bigint + + + Number of vacuums in this database that entered the wraparound + failsafe mode (see ) + + + + + + vacuum_interrupt_count bigint + + + Number of times a vacuum in this database was interrupted by an error, + the vacuum of an append-optimized table included. In a Cloudberry + cluster the count is kept by the instance on which the vacuum failed: + a vacuum dispatched to the segments that fails there is counted by + those segments, not by the coordinator. A segment reports the count + once its part of the failed distributed transaction has ended, which + may be as late as the next command of the session. + + + + + + stats_reset timestamp with time zone + + + Time at which these statistics were last reset + + + + +
+
+ <structname>pg_stat_database_conflicts</structname> @@ -4926,6 +5081,62 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i
+ + + total_vacuum_time double precision + + + Total time this index has been processed by manually invoked vacuums, + in milliseconds. (This includes the time spent sleeping due to + cost-based delays.) + + + + + + total_autovacuum_time double precision + + + Total time this index has been processed by the autovacuum daemon, + in milliseconds. (This includes the time spent sleeping due to + cost-based delays.) + + + + + + total_vacuum_delay_time double precision + + + Total time manually invoked vacuums spent sleeping in cost-based delay + points while processing this index, in milliseconds (counted only when + is enabled) + + + + + + total_autovacuum_delay_time double precision + + + Total time the autovacuum daemon spent sleeping in cost-based delay + points while processing this index, in milliseconds (counted only when + is enabled) + + + + + + vacuum_failsafe_count bigint + + + Number of vacuums of this table that entered the wraparound failsafe + mode (see ). Always zero for + append-optimized tables, which have no tuple transaction IDs to + freeze. + + + n_tup_ins bigint @@ -5017,6 +5228,42 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i + + + + + visible_page_marks_cleared bigint + + + Number of times the all-visible mark in the + visibility map was cleared for + pages of this table. The all-visible mark of a heap page is + cleared whenever a backend process modifies a page that was + previously marked all-visible by vacuum activity (whether manual + VACUUM or autovacuum). The page must then be + processed again by vacuum on a subsequent run. A high rate of + change in this counter means that vacuum has to repeatedly + re-process pages of this table. Always zero for append-optimized + tables, which have no visibility map. + + + + + + frozen_page_marks_cleared bigint + + + Number of times the all-frozen mark in the + visibility map was cleared for + pages of this table. The all-frozen mark of a heap page is cleared + whenever a backend process modifies a page that was previously + marked all-frozen by vacuum activity (manual VACUUM + or autovacuum). The page must then be processed again by vacuum on + the next freeze run for this table. Always zero for append-optimized + tables. + + + last_vacuum timestamp with time zone @@ -5094,6 +5341,66 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i daemon + + + + total_vacuum_time double precision + + + Total time this table has been manually vacuumed, in milliseconds + + + + + + total_autovacuum_time double precision + + + Total time this table has been vacuumed by the autovacuum daemon, + in milliseconds + + + + + + total_analyze_time double precision + + + Total time this table has been manually analyzed, in milliseconds + + + + + + total_autoanalyze_time double precision + + + Total time this table has been analyzed by the autovacuum daemon, + in milliseconds + + + + + + total_vacuum_delay_time double precision + + + Total time this table's vacuums spent sleeping in cost-based delay + points, in milliseconds (counted only when + is enabled) + + + + + + total_autovacuum_delay_time double precision + + + Total time autovacuums of this table spent sleeping in cost-based + delay points, in milliseconds (counted only when + is enabled) + + @@ -6370,6 +6677,13 @@ FROM pg_stat_get_backend_idset() AS backendid; information about how to interpret it. + + In Cloudberry, gp_stat_progress_analyze_summary + sums delay_time across segment workers in each + reported phase. This is total worker sleep time, including every copy of a + replicated table, rather than the elapsed time of the distributed command. + + <structname>pg_stat_progress_analyze</structname> View @@ -6496,6 +6810,18 @@ FROM pg_stat_get_backend_idset() AS backendid; acquiring inherited sample rows. + + + + delay_time double precision + + + Total time spent sleeping due to cost-based delay (see + , in milliseconds + (if is enabled, otherwise + zero). + +
@@ -7252,6 +7578,13 @@ FROM pg_stat_get_backend_idset() AS backendid; in place. See . + + In Cloudberry, gp_stat_progress_vacuum_summary + sums delay_time across segment workers in each + reported phase. This is total worker sleep time, including every copy of a + replicated table, rather than the elapsed time of the distributed command. + + <structname>pg_stat_progress_vacuum</structname> View @@ -7377,6 +7710,18 @@ FROM pg_stat_get_backend_idset() AS backendid; Number of dead tuples collected since the last index vacuum cycle. + + + + delay_time double precision + + + Total time spent sleeping due to cost-based delay (see + ), in milliseconds + (if is enabled, otherwise + zero). + +
diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql index 24b7fc1d33b..f2b72af85f4 100644 --- a/src/backend/catalog/system_views.sql +++ b/src/backend/catalog/system_views.sql @@ -701,7 +701,16 @@ CREATE VIEW pg_stat_all_tables AS pg_stat_get_vacuum_count(C.oid) AS vacuum_count, pg_stat_get_autovacuum_count(C.oid) AS autovacuum_count, pg_stat_get_analyze_count(C.oid) AS analyze_count, - pg_stat_get_autoanalyze_count(C.oid) AS autoanalyze_count + pg_stat_get_autoanalyze_count(C.oid) AS autoanalyze_count, + pg_stat_get_total_vacuum_time(C.oid) AS total_vacuum_time, + pg_stat_get_total_autovacuum_time(C.oid) AS total_autovacuum_time, + pg_stat_get_total_analyze_time(C.oid) AS total_analyze_time, + pg_stat_get_total_autoanalyze_time(C.oid) AS total_autoanalyze_time, + pg_stat_get_total_vacuum_delay_time(C.oid) AS total_vacuum_delay_time, + pg_stat_get_total_autovacuum_delay_time(C.oid) AS total_autovacuum_delay_time, + pg_stat_get_vacuum_failsafe_count(C.oid) AS vacuum_failsafe_count, + pg_stat_get_visible_page_marks_cleared(C.oid) AS visible_page_marks_cleared, + pg_stat_get_frozen_page_marks_cleared(C.oid) AS frozen_page_marks_cleared FROM pg_class C LEFT JOIN pg_index I ON C.oid = I.indrelid LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace) @@ -821,7 +830,11 @@ CREATE VIEW pg_stat_all_indexes AS pg_stat_get_numscans(I.oid) AS idx_scan, pg_stat_get_lastscan(I.oid) AS last_idx_scan, pg_stat_get_tuples_returned(I.oid) AS idx_tup_read, - pg_stat_get_tuples_fetched(I.oid) AS idx_tup_fetch + pg_stat_get_tuples_fetched(I.oid) AS idx_tup_fetch, + pg_stat_get_total_vacuum_time(I.oid) AS total_vacuum_time, + pg_stat_get_total_autovacuum_time(I.oid) AS total_autovacuum_time, + pg_stat_get_total_vacuum_delay_time(I.oid) AS total_vacuum_delay_time, + pg_stat_get_total_autovacuum_delay_time(I.oid) AS total_autovacuum_delay_time FROM pg_class C JOIN pg_index X ON C.oid = X.indrelid JOIN pg_class I ON I.oid = X.indexrelid @@ -1205,6 +1218,24 @@ CREATE VIEW pg_stat_database AS UNION ALL SELECT oid, datname FROM pg_database ) D; + +CREATE VIEW pg_stat_vacuum AS + SELECT + D.oid AS datid, + D.datname AS datname, + pg_stat_get_db_total_vacuum_time(D.oid) AS total_vacuum_time, + pg_stat_get_db_total_autovacuum_time(D.oid) AS total_autovacuum_time, + pg_stat_get_db_total_vacuum_delay_time(D.oid) AS total_vacuum_delay_time, + pg_stat_get_db_total_autovacuum_delay_time(D.oid) AS total_autovacuum_delay_time, + pg_stat_get_db_vacuum_failsafe_count(D.oid) AS vacuum_failsafe_count, + pg_stat_get_db_vacuum_interrupt_count(D.oid) AS vacuum_interrupt_count, + pg_stat_get_db_stat_reset_time(D.oid) AS stats_reset + FROM ( + SELECT 0 AS oid, NULL::name AS datname + UNION ALL + SELECT oid, datname FROM pg_database + ) D; + CREATE VIEW pg_resqueue_status AS SELECT q.rsqname, @@ -1564,7 +1595,8 @@ CREATE VIEW pg_stat_progress_analyze AS S.param5 AS ext_stats_computed, S.param6 AS child_tables_total, S.param7 AS child_tables_done, - CAST(S.param8 AS oid) AS current_child_table_relid + CAST(S.param8 AS oid) AS current_child_table_relid, + S.param9 / 1000000::double precision AS delay_time FROM pg_stat_get_progress_info('ANALYZE') AS S LEFT JOIN pg_database D ON S.datid = D.oid; @@ -1585,7 +1617,8 @@ CREATE VIEW pg_stat_progress_vacuum AS END AS phase, S.param2 AS heap_blks_total, S.param3 AS heap_blks_scanned, S.param4 AS heap_blks_vacuumed, S.param5 AS index_vacuum_count, - S.param6 AS max_dead_tuples, S.param7 AS num_dead_tuples + S.param6 AS max_dead_tuples, S.param7 AS num_dead_tuples, + S.param8 / 1000000::double precision AS delay_time FROM pg_stat_get_progress_info('VACUUM') AS S LEFT JOIN pg_database D ON S.datid = D.oid; @@ -1933,4 +1966,4 @@ $$ WHERE pg_subscription.subname = sub_info.subname ) from gp_dist_random('gp_id'); -$$ LANGUAGE SQL; \ No newline at end of file +$$ LANGUAGE SQL; diff --git a/src/backend/catalog/system_views_gp.in b/src/backend/catalog/system_views_gp.in index 41e4a2468e5..71fac72cd5f 100644 --- a/src/backend/catalog/system_views_gp.in +++ b/src/backend/catalog/system_views_gp.in @@ -14,6 +14,7 @@ pg_stat_all_tables pg_stat_archiver pg_stat_bgwriter pg_stat_database +pg_stat_vacuum pg_stat_database_conflicts pg_stat_gssapi pg_stat_operations diff --git a/src/backend/catalog/system_views_gp_summary.sql b/src/backend/catalog/system_views_gp_summary.sql index 62bde4e3d96..8447253d413 100644 --- a/src/backend/catalog/system_views_gp_summary.sql +++ b/src/backend/catalog/system_views_gp_summary.sql @@ -94,7 +94,26 @@ GROUP BY sdb.datname; +CREATE VIEW gp_stat_vacuum_summary AS +SELECT + sdb.datid, + sdb.datname, + sum(sdb.total_vacuum_time) as total_vacuum_time, + sum(sdb.total_autovacuum_time) as total_autovacuum_time, + sum(sdb.total_vacuum_delay_time) as total_vacuum_delay_time, + sum(sdb.total_autovacuum_delay_time) as total_autovacuum_delay_time, + sum(sdb.vacuum_failsafe_count)::bigint as vacuum_failsafe_count, + sum(sdb.vacuum_interrupt_count)::bigint as vacuum_interrupt_count, + max(sdb.stats_reset) as stats_reset +FROM + gp_stat_vacuum sdb +GROUP BY + sdb.datid, + sdb.datname; + -- Gather data from segments on user tables, and use data on coordinator on system tables. +-- ANALYZE counts and times come from the coordinator: QEs classify even +-- auto-analyze sampling as manual ANALYZE. CREATE VIEW gp_stat_all_tables_summary AS SELECT s.relid, @@ -120,7 +139,16 @@ SELECT s.vacuum_count, s.autovacuum_count, s.analyze_count, - s.autoanalyze_count + s.autoanalyze_count, + m.total_vacuum_time, + m.total_autovacuum_time, + s.total_analyze_time, + s.total_autoanalyze_time, + m.total_vacuum_delay_time, + m.total_autovacuum_delay_time, + m.vacuum_failsafe_count, + m.visible_page_marks_cleared, + m.frozen_page_marks_cleared FROM (SELECT allt.relid, @@ -148,7 +176,16 @@ FROM max(vacuum_count) as vacuum_count, max(autovacuum_count) as autovacuum_count, max(analyze_count) as analyze_count, - max(autoanalyze_count) as autoanalyze_count + max(autoanalyze_count) as autoanalyze_count, + case when d.policytype = 'r' then (sum(total_vacuum_time)/d.numsegments) else sum(total_vacuum_time) end total_vacuum_time, + case when d.policytype = 'r' then (sum(total_autovacuum_time)/d.numsegments) else sum(total_autovacuum_time) end total_autovacuum_time, + case when d.policytype = 'r' then (sum(total_analyze_time)/d.numsegments) else sum(total_analyze_time) end total_analyze_time, + case when d.policytype = 'r' then (sum(total_autoanalyze_time)/d.numsegments) else sum(total_autoanalyze_time) end total_autoanalyze_time, + case when d.policytype = 'r' then (sum(total_vacuum_delay_time)/d.numsegments) else sum(total_vacuum_delay_time) end total_vacuum_delay_time, + case when d.policytype = 'r' then (sum(total_autovacuum_delay_time)/d.numsegments) else sum(total_autovacuum_delay_time) end total_autovacuum_delay_time, + sum(vacuum_failsafe_count)::bigint as vacuum_failsafe_count, + case when d.policytype = 'r' then (sum(visible_page_marks_cleared)/d.numsegments)::bigint else sum(visible_page_marks_cleared) end visible_page_marks_cleared, + case when d.policytype = 'r' then (sum(frozen_page_marks_cleared)/d.numsegments)::bigint else sum(frozen_page_marks_cleared) end frozen_page_marks_cleared FROM gp_dist_random('pg_stat_all_tables') allt inner join pg_class c @@ -229,7 +266,11 @@ SELECT m.idx_scan, m.last_idx_scan, m.idx_tup_read, - m.idx_tup_fetch + m.idx_tup_fetch, + m.total_vacuum_time, + m.total_autovacuum_time, + m.total_vacuum_delay_time, + m.total_autovacuum_delay_time FROM (SELECT alli.relid, @@ -240,7 +281,11 @@ FROM case when d.policytype = 'r' then (sum(alli.idx_scan)/d.numsegments)::bigint else sum(alli.idx_scan) end idx_scan, max(last_idx_scan) as last_idx_scan, case when d.policytype = 'r' then (sum(alli.idx_tup_read)/d.numsegments)::bigint else sum(alli.idx_tup_read) end idx_tup_read, - case when d.policytype = 'r' then (sum(alli.idx_tup_fetch)/d.numsegments)::bigint else sum(alli.idx_tup_fetch) end idx_tup_fetch + case when d.policytype = 'r' then (sum(alli.idx_tup_fetch)/d.numsegments)::bigint else sum(alli.idx_tup_fetch) end idx_tup_fetch, + case when d.policytype = 'r' then (sum(alli.total_vacuum_time)/d.numsegments) else sum(alli.total_vacuum_time) end total_vacuum_time, + case when d.policytype = 'r' then (sum(alli.total_autovacuum_time)/d.numsegments) else sum(alli.total_autovacuum_time) end total_autovacuum_time, + case when d.policytype = 'r' then (sum(alli.total_vacuum_delay_time)/d.numsegments) else sum(alli.total_vacuum_delay_time) end total_vacuum_delay_time, + case when d.policytype = 'r' then (sum(alli.total_autovacuum_delay_time)/d.numsegments) else sum(alli.total_autovacuum_delay_time) end total_autovacuum_delay_time FROM gp_dist_random('pg_stat_all_indexes') alli inner join pg_class c @@ -259,7 +304,7 @@ FROM pg_stat_all_indexes WHERE relid < 16384) m, pg_stat_all_indexes s -WHERE m.relid = s.relid; +WHERE m.relid = s.relid AND m.indexrelid = s.indexrelid; CREATE VIEW gp_stat_sys_indexes_summary AS SELECT * FROM gp_stat_all_indexes_summary @@ -413,6 +458,7 @@ GROUP BY CREATE VIEW gp_stat_progress_vacuum_summary AS +-- Delay is time consumed across workers, including all replicated copies. SELECT max(coalesce(a1.pid, 0)) as pid, a.datid, @@ -424,7 +470,8 @@ SELECT case when d.policytype = 'r' then (sum(a.heap_blks_vacuumed)/d.numsegments)::bigint else sum(a.heap_blks_vacuumed) end heap_blks_vacuumed, case when d.policytype = 'r' then (sum(a.index_vacuum_count)/d.numsegments)::bigint else sum(a.index_vacuum_count) end index_vacuum_count, case when d.policytype = 'r' then (sum(a.max_dead_tuples)/d.numsegments)::bigint else sum(a.max_dead_tuples) end max_dead_tuples, - case when d.policytype = 'r' then (sum(a.num_dead_tuples)/d.numsegments)::bigint else sum(a.num_dead_tuples) end num_dead_tuples + case when d.policytype = 'r' then (sum(a.num_dead_tuples)/d.numsegments)::bigint else sum(a.num_dead_tuples) end num_dead_tuples, + sum(a.delay_time) as delay_time FROM gp_stat_progress_vacuum a JOIN pg_class c ON a.relid = c.oid LEFT JOIN gp_distribution_policy d ON c.oid = d.localoid @@ -433,6 +480,7 @@ WHERE a.gp_segment_id > -1 GROUP BY a.datid, a.datname, a.relid, a.phase, d.policytype, d.numsegments; CREATE OR REPLACE VIEW gp_stat_progress_analyze_summary AS +-- Delay is time consumed across workers, including all replicated copies. SELECT max(coalesce(a1.pid, 0)) as pid, a.datid, @@ -444,7 +492,8 @@ SELECT case when d.policytype = 'r' then (sum(a.ext_stats_total)/d.numsegments)::bigint else sum(a.ext_stats_total) end ext_stats_total, case when d.policytype = 'r' then (sum(a.ext_stats_computed)/d.numsegments)::bigint else sum(a.ext_stats_computed) end ext_stats_computed, case when d.policytype = 'r' then (sum(a.child_tables_total)/d.numsegments)::bigint else sum(a.child_tables_total) end child_tables_total, - case when d.policytype = 'r' then (sum(a.child_tables_done)/d.numsegments)::bigint else sum(a.child_tables_done) end child_tables_done + case when d.policytype = 'r' then (sum(a.child_tables_done)/d.numsegments)::bigint else sum(a.child_tables_done) end child_tables_done, + sum(a.delay_time) as delay_time FROM gp_stat_progress_analyze a JOIN pg_class c ON a.relid = c.oid LEFT JOIN gp_distribution_policy d ON c.oid = d.localoid diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c index 777ac00a340..e94a5645ab4 100644 --- a/src/backend/utils/adt/pgstatfuncs.c +++ b/src/backend/utils/adt/pgstatfuncs.c @@ -120,6 +120,49 @@ PG_STAT_GET_RELENTRY_INT64(tuples_updated) /* pg_stat_get_vacuum_count */ PG_STAT_GET_RELENTRY_INT64(vacuum_count) +/* pg_stat_get_vacuum_failsafe_count */ +PG_STAT_GET_RELENTRY_INT64(vacuum_failsafe_count) + +/* pg_stat_get_visible_page_marks_cleared */ +PG_STAT_GET_RELENTRY_INT64(visible_page_marks_cleared) + +/* pg_stat_get_frozen_page_marks_cleared */ +PG_STAT_GET_RELENTRY_INT64(frozen_page_marks_cleared) + +#define PG_STAT_GET_RELENTRY_FLOAT8(stat) \ +Datum \ +CppConcat(pg_stat_get_,stat)(PG_FUNCTION_ARGS) \ +{ \ + Oid relid = PG_GETARG_OID(0); \ + double result; \ + PgStat_StatTabEntry *tabentry; \ + \ + if ((tabentry = pgstat_fetch_stat_tabentry(relid)) == NULL) \ + result = 0; \ + else \ + result = (double) (tabentry->stat); \ + \ + PG_RETURN_FLOAT8(result); \ +} + +/* pg_stat_get_total_vacuum_time */ +PG_STAT_GET_RELENTRY_FLOAT8(total_vacuum_time) + +/* pg_stat_get_total_autovacuum_time */ +PG_STAT_GET_RELENTRY_FLOAT8(total_autovacuum_time) + +/* pg_stat_get_total_analyze_time */ +PG_STAT_GET_RELENTRY_FLOAT8(total_analyze_time) + +/* pg_stat_get_total_autoanalyze_time */ +PG_STAT_GET_RELENTRY_FLOAT8(total_autoanalyze_time) + +/* pg_stat_get_total_vacuum_delay_time */ +PG_STAT_GET_RELENTRY_FLOAT8(total_vacuum_delay_time) + +/* pg_stat_get_total_autovacuum_delay_time */ +PG_STAT_GET_RELENTRY_FLOAT8(total_autovacuum_delay_time) + #define PG_STAT_GET_RELENTRY_TIMESTAMPTZ(stat) \ Datum \ CppConcat(pg_stat_get_,stat)(PG_FUNCTION_ARGS) \ @@ -1099,6 +1142,9 @@ PG_STAT_GET_DBENTRY_INT64(conflict_tablespace) /* pg_stat_get_db_deadlocks */ PG_STAT_GET_DBENTRY_INT64(deadlocks) +/* pg_stat_get_db_vacuum_interrupt_count */ +PG_STAT_GET_DBENTRY_INT64(vacuum_interrupt_count) + /* pg_stat_get_db_sessions */ PG_STAT_GET_DBENTRY_INT64(sessions) @@ -1248,6 +1294,21 @@ PG_STAT_GET_DBENTRY_FLOAT8_MS(blk_write_time) /* pg_stat_get_db_idle_in_transaction_time */ PG_STAT_GET_DBENTRY_FLOAT8_MS(idle_in_transaction_time) +/* pg_stat_get_db_total_vacuum_time */ +PG_STAT_GET_DBENTRY_FLOAT8_MS(total_vacuum_time) + +/* pg_stat_get_db_total_autovacuum_time */ +PG_STAT_GET_DBENTRY_FLOAT8_MS(total_autovacuum_time) + +/* pg_stat_get_db_total_vacuum_delay_time */ +PG_STAT_GET_DBENTRY_FLOAT8_MS(total_vacuum_delay_time) + +/* pg_stat_get_db_total_autovacuum_delay_time */ +PG_STAT_GET_DBENTRY_FLOAT8_MS(total_autovacuum_delay_time) + +/* pg_stat_get_db_vacuum_failsafe_count */ +PG_STAT_GET_DBENTRY_INT64(vacuum_failsafe_count) + /* pg_stat_get_db_session_time */ PG_STAT_GET_DBENTRY_FLOAT8_MS(session_time) diff --git a/src/include/catalog/catversion.h b/src/include/catalog/catversion.h index c0dc421c3e0..21dd3822811 100644 --- a/src/include/catalog/catversion.h +++ b/src/include/catalog/catversion.h @@ -60,6 +60,6 @@ */ /* 3yyymmddN */ -#define CATALOG_VERSION_NO 302610191 +#define CATALOG_VERSION_NO 302610070 #endif diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 8451447907d..d7ccc889973 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -5473,6 +5473,22 @@ proname => 'pg_stat_get_autoanalyze_count', provolatile => 's', proparallel => 'r', prorettype => 'int8', proargtypes => 'oid', prosrc => 'pg_stat_get_autoanalyze_count' }, +{ oid => '8406', descr => 'total vacuum time, in milliseconds', + proname => 'pg_stat_get_total_vacuum_time', provolatile => 's', + proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', + prosrc => 'pg_stat_get_total_vacuum_time' }, +{ oid => '8407', descr => 'total autovacuum time, in milliseconds', + proname => 'pg_stat_get_total_autovacuum_time', provolatile => 's', + proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', + prosrc => 'pg_stat_get_total_autovacuum_time' }, +{ oid => '8408', descr => 'total analyze time, in milliseconds', + proname => 'pg_stat_get_total_analyze_time', provolatile => 's', + proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', + prosrc => 'pg_stat_get_total_analyze_time' }, +{ oid => '8409', descr => 'total autoanalyze time, in milliseconds', + proname => 'pg_stat_get_total_autoanalyze_time', provolatile => 's', + proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', + prosrc => 'pg_stat_get_total_autoanalyze_time' }, { oid => '1936', descr => 'statistics: currently active backend IDs', proname => 'pg_stat_get_backend_idset', prorows => '100', proretset => 't', provolatile => 's', proparallel => 'r', prorettype => 'int4', @@ -5709,6 +5725,54 @@ proname => 'pg_stat_get_db_blk_write_time', provolatile => 's', proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', prosrc => 'pg_stat_get_db_blk_write_time' }, +{ oid => '4707', + descr => 'statistics: number of times the all-visible marks in the visibility map were cleared for pages of this table', + proname => 'pg_stat_get_visible_page_marks_cleared', provolatile => 's', + proparallel => 'r', prorettype => 'int8', proargtypes => 'oid', + prosrc => 'pg_stat_get_visible_page_marks_cleared' }, +{ oid => '4708', + descr => 'statistics: number of times the all-frozen marks in the visibility map were cleared for pages of this table', + proname => 'pg_stat_get_frozen_page_marks_cleared', provolatile => 's', + proparallel => 'r', prorettype => 'int8', proargtypes => 'oid', + prosrc => 'pg_stat_get_frozen_page_marks_cleared' }, +{ oid => '4706', descr => 'statistics: number of vacuums interrupted by errors in database', + proname => 'pg_stat_get_db_vacuum_interrupt_count', provolatile => 's', + proparallel => 'r', prorettype => 'int8', proargtypes => 'oid', + prosrc => 'pg_stat_get_db_vacuum_interrupt_count' }, +{ oid => '4700', descr => 'total vacuum delay time, in milliseconds', + proname => 'pg_stat_get_total_vacuum_delay_time', provolatile => 's', + proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', + prosrc => 'pg_stat_get_total_vacuum_delay_time' }, +{ oid => '4701', descr => 'total autovacuum delay time, in milliseconds', + proname => 'pg_stat_get_total_autovacuum_delay_time', provolatile => 's', + proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', + prosrc => 'pg_stat_get_total_autovacuum_delay_time' }, +{ oid => '4702', descr => 'statistics: total vacuum time of tables in database, in milliseconds', + proname => 'pg_stat_get_db_total_vacuum_time', provolatile => 's', + proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', + prosrc => 'pg_stat_get_db_total_vacuum_time' }, +{ oid => '4703', descr => 'statistics: total autovacuum time of tables in database, in milliseconds', + proname => 'pg_stat_get_db_total_autovacuum_time', provolatile => 's', + proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', + prosrc => 'pg_stat_get_db_total_autovacuum_time' }, +{ oid => '4704', descr => 'statistics: total vacuum delay time in database, in milliseconds', + proname => 'pg_stat_get_db_total_vacuum_delay_time', provolatile => 's', + proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', + prosrc => 'pg_stat_get_db_total_vacuum_delay_time' }, +{ oid => '4705', descr => 'statistics: total autovacuum delay time in database, in milliseconds', + proname => 'pg_stat_get_db_total_autovacuum_delay_time', provolatile => 's', + proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', + prosrc => 'pg_stat_get_db_total_autovacuum_delay_time' }, +{ oid => '8691', + descr => 'statistics: number of vacuums that entered the wraparound failsafe mode', + proname => 'pg_stat_get_vacuum_failsafe_count', provolatile => 's', + proparallel => 'r', prorettype => 'int8', proargtypes => 'oid', + prosrc => 'pg_stat_get_vacuum_failsafe_count' }, +{ oid => '8692', + descr => 'statistics: number of vacuums in database that entered the wraparound failsafe mode', + proname => 'pg_stat_get_db_vacuum_failsafe_count', provolatile => 's', + proparallel => 'r', prorettype => 'int8', proargtypes => 'oid', + prosrc => 'pg_stat_get_db_vacuum_failsafe_count' }, { oid => '6185', descr => 'statistics: session time, in milliseconds', proname => 'pg_stat_get_db_session_time', provolatile => 's', proparallel => 'r', prorettype => 'float8', proargtypes => 'oid', diff --git a/src/test/isolation/expected/vacuum-extending-freeze.out b/src/test/isolation/expected/vacuum-extending-freeze.out new file mode 100644 index 00000000000..2ddaa113e80 --- /dev/null +++ b/src/test/isolation/expected/vacuum-extending-freeze.out @@ -0,0 +1,128 @@ +Parsed test spec with 2 sessions + +starting permutation: s2_vacuum_freeze s1_update_table s1_get_cleared_vm_flags_stats s2_vacuum_freeze s2_vacuum_freeze s1_select_from_index s2_delete_from_table s1_get_cleared_vm_flags_stats s2_vacuum_freeze s1_commit s1_get_cleared_vm_flags_stats +pg_stat_force_next_flush +------------------------ + +(1 row) + +step s2_vacuum_freeze: + VACUUM FREEZE vestat; + +step s1_update_table: + UPDATE vestat SET x = x + 1001 where x >= 2500; + SELECT pg_stat_force_next_flush(); + +pg_stat_force_next_flush +------------------------ + +(1 row) + +step s1_get_cleared_vm_flags_stats: + SELECT pg_stat_force_next_flush(); + + SELECT v.visible_page_marks_cleared > cleared_all_visibile_flag_count as visible_page_marks_cleared, + v.frozen_page_marks_cleared > cleared_frozen_flag_count as frozen_page_marks_cleared + FROM pg_stat_all_tables v, stats_state + WHERE v.relname = 'vestat'; + + UPDATE stats_state + SET cleared_all_visibile_flag_count = v.visible_page_marks_cleared, + cleared_frozen_flag_count = v.frozen_page_marks_cleared + FROM pg_stat_all_tables v + WHERE v.relname = 'vestat'; + +pg_stat_force_next_flush +------------------------ + +(1 row) + +visible_page_marks_cleared|frozen_page_marks_cleared +--------------------------+------------------------- +t |t +(1 row) + +step s2_vacuum_freeze: + VACUUM FREEZE vestat; + +step s2_vacuum_freeze: + VACUUM FREEZE vestat; + +step s1_select_from_index: + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT count(x) FROM vestat WHERE x > 2000; + + UPDATE stats_state + SET cleared_all_visibile_flag_count = v.visible_page_marks_cleared, + cleared_frozen_flag_count = v.frozen_page_marks_cleared + FROM pg_stat_all_tables v + WHERE v.relname = 'vestat'; + +count +----- + 3000 +(1 row) + +step s2_delete_from_table: + DELETE FROM vestat WHERE x > 4930; + SELECT pg_stat_force_next_flush(); + +pg_stat_force_next_flush +------------------------ + +(1 row) + +step s1_get_cleared_vm_flags_stats: + SELECT pg_stat_force_next_flush(); + + SELECT v.visible_page_marks_cleared > cleared_all_visibile_flag_count as visible_page_marks_cleared, + v.frozen_page_marks_cleared > cleared_frozen_flag_count as frozen_page_marks_cleared + FROM pg_stat_all_tables v, stats_state + WHERE v.relname = 'vestat'; + + UPDATE stats_state + SET cleared_all_visibile_flag_count = v.visible_page_marks_cleared, + cleared_frozen_flag_count = v.frozen_page_marks_cleared + FROM pg_stat_all_tables v + WHERE v.relname = 'vestat'; + +pg_stat_force_next_flush +------------------------ + +(1 row) + +visible_page_marks_cleared|frozen_page_marks_cleared +--------------------------+------------------------- +f |f +(1 row) + +step s2_vacuum_freeze: + VACUUM FREEZE vestat; + +step s1_commit: + COMMIT; + +step s1_get_cleared_vm_flags_stats: + SELECT pg_stat_force_next_flush(); + + SELECT v.visible_page_marks_cleared > cleared_all_visibile_flag_count as visible_page_marks_cleared, + v.frozen_page_marks_cleared > cleared_frozen_flag_count as frozen_page_marks_cleared + FROM pg_stat_all_tables v, stats_state + WHERE v.relname = 'vestat'; + + UPDATE stats_state + SET cleared_all_visibile_flag_count = v.visible_page_marks_cleared, + cleared_frozen_flag_count = v.frozen_page_marks_cleared + FROM pg_stat_all_tables v + WHERE v.relname = 'vestat'; + +pg_stat_force_next_flush +------------------------ + +(1 row) + +visible_page_marks_cleared|frozen_page_marks_cleared +--------------------------+------------------------- +t |t +(1 row) + diff --git a/src/test/isolation/isolation_schedule b/src/test/isolation/isolation_schedule index cfac5350480..1c9e1e11eca 100644 --- a/src/test/isolation/isolation_schedule +++ b/src/test/isolation/isolation_schedule @@ -178,3 +178,4 @@ test: vacuum-ao-concurrent-drop test: serializable-parallel-3 test: matview-write-skew test: type-ddl-locking +test: vacuum-extending-freeze diff --git a/src/test/isolation/specs/vacuum-extending-freeze.spec b/src/test/isolation/specs/vacuum-extending-freeze.spec new file mode 100644 index 00000000000..2ba87eb3d23 --- /dev/null +++ b/src/test/isolation/specs/vacuum-extending-freeze.spec @@ -0,0 +1,108 @@ +# Check cumulative counts of cleared VM bits after freezing. +# A repeatable-read transaction keeps deleted tuples visible to its snapshot. +# It also caches the table statistics before the other session deletes rows: +# the VM bits clear during DELETE, while the cached counters stay unchanged +# until the reader commits. Force the writer's counters to flush so this +# distinction does not depend on the statistics flush interval. + +setup +{ + CREATE TABLE vestat (x int, y int) + WITH (autovacuum_enabled = off, fillfactor = 70); + + INSERT INTO vestat + SELECT i, i FROM generate_series(1, 5000) AS g(i); + + CREATE INDEX vestat_idx ON vestat (x); + + CREATE TABLE stats_state (cleared_frozen_flag_count int, cleared_all_visibile_flag_count int); + INSERT INTO stats_state VALUES (0,0); + ANALYZE vestat; + + -- Ensure stats are flushed before starting the scenario + SELECT pg_stat_force_next_flush(); +} + +teardown +{ + DROP TABLE IF EXISTS vestat; + DROP TABLE IF EXISTS stats_state; + RESET vacuum_freeze_min_age; + RESET vacuum_freeze_table_age; + +} + +session s1 +setup +{ + SET stats_fetch_consistency = 'cache'; +} + +step s1_get_cleared_vm_flags_stats +{ + SELECT pg_stat_force_next_flush(); + + SELECT v.visible_page_marks_cleared > cleared_all_visibile_flag_count as visible_page_marks_cleared, + v.frozen_page_marks_cleared > cleared_frozen_flag_count as frozen_page_marks_cleared + FROM pg_stat_all_tables v, stats_state + WHERE v.relname = 'vestat'; + + UPDATE stats_state + SET cleared_all_visibile_flag_count = v.visible_page_marks_cleared, + cleared_frozen_flag_count = v.frozen_page_marks_cleared + FROM pg_stat_all_tables v + WHERE v.relname = 'vestat'; +} + +step s1_select_from_index +{ + BEGIN ISOLATION LEVEL REPEATABLE READ; + SELECT count(x) FROM vestat WHERE x > 2000; + + UPDATE stats_state + SET cleared_all_visibile_flag_count = v.visible_page_marks_cleared, + cleared_frozen_flag_count = v.frozen_page_marks_cleared + FROM pg_stat_all_tables v + WHERE v.relname = 'vestat'; +} + +step s1_commit +{ + COMMIT; +} + +session s2 +setup +{ + -- Configure aggressive freezing vacuum behavior + SET vacuum_freeze_min_age = 0; + SET vacuum_freeze_table_age = 0; +} +step s2_delete_from_table +{ + DELETE FROM vestat WHERE x > 4930; + SELECT pg_stat_force_next_flush(); +} +step s2_vacuum_freeze +{ + VACUUM FREEZE vestat; +} + +step s1_update_table +{ + UPDATE vestat SET x = x + 1001 where x >= 2500; + SELECT pg_stat_force_next_flush(); +} + +permutation + s2_vacuum_freeze + s1_update_table + s1_get_cleared_vm_flags_stats + s2_vacuum_freeze + s2_vacuum_freeze + s1_select_from_index + s2_delete_from_table + s1_get_cleared_vm_flags_stats + s2_vacuum_freeze + s1_commit + s1_get_cleared_vm_flags_stats diff --git a/src/test/isolation2/expected/vacuum_analyze_stats.out b/src/test/isolation2/expected/vacuum_analyze_stats.out new file mode 100644 index 00000000000..c41756b5908 --- /dev/null +++ b/src/test/isolation2/expected/vacuum_analyze_stats.out @@ -0,0 +1,99 @@ +-- Licensed to the Apache Software Foundation (ASF) under one or more +-- contributor license agreements. See the NOTICE file distributed +-- with this work for additional information regarding copyright +-- ownership. The ASF licenses this file to You under the Apache +-- License, Version 2.0 (the "License"); you may not use this file +-- except in compliance with the License. You may obtain a copy of the +-- License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +-- implied. See the License for the specific language governing +-- permissions and limitations under the License. + +-- Counts and elapsed times must use the same coordinator ANALYZE record. +-- QE sampling records auto-analyze as manual ANALYZE. +SET gp_autostats_mode = none; +SET +CREATE TABLE analyze_time_hash (a int) WITH (autovacuum_enabled = false) DISTRIBUTED BY (a); +CREATE +CREATE TABLE analyze_time_repl (a int) WITH (autovacuum_enabled = false) DISTRIBUTED REPLICATED; +CREATE +INSERT INTO analyze_time_hash SELECT generate_series(1, 50000); +INSERT 50000 +INSERT INTO analyze_time_repl SELECT generate_series(1, 50000); +INSERT 50000 +ANALYZE analyze_time_hash; +ANALYZE +ANALYZE analyze_time_repl; +ANALYZE +SELECT count(*) = 2 AND bool_and(s.analyze_count = 1 AND s.autoanalyze_count = 0 AND s.total_analyze_time > 0 AND s.total_autoanalyze_time = 0 AND s.total_analyze_time = q.total_analyze_time) AS manual_times_match FROM gp_stat_all_tables_summary s JOIN pg_stat_all_tables q USING (relid) WHERE s.relname IN ('analyze_time_hash', 'analyze_time_repl'); + manual_times_match +-------------------- + t +(1 row) + +-- Start a fresh interval, then let an actual coordinator autovacuum worker +-- analyze both tables. No explicit ANALYZE may contribute to this interval. +SELECT pg_stat_reset_single_table_counters('analyze_time_hash'::regclass); + pg_stat_reset_single_table_counters +------------------------------------- + +(1 row) +SELECT pg_stat_reset_single_table_counters('analyze_time_repl'::regclass); + pg_stat_reset_single_table_counters +------------------------------------- + +(1 row) +ALTER TABLE analyze_time_hash SET (autovacuum_enabled = true, autovacuum_analyze_threshold = 100, autovacuum_analyze_scale_factor = 0); +ALTER +ALTER TABLE analyze_time_repl SET (autovacuum_enabled = true, autovacuum_analyze_threshold = 100, autovacuum_analyze_scale_factor = 0); +ALTER +ALTER SYSTEM SET autovacuum = on; +ALTER +ALTER SYSTEM SET autovacuum_naptime = '1s'; +ALTER +SELECT pg_reload_conf(); + pg_reload_conf +---------------- + t +(1 row) +INSERT INTO analyze_time_hash SELECT generate_series(50001, 60000); +INSERT 10000 +INSERT INTO analyze_time_repl SELECT generate_series(50001, 60000); +INSERT 10000 +SELECT gp_stat_force_next_flush(); + gp_stat_force_next_flush +-------------------------- + +(1 row) +CREATE FUNCTION wait_for_analyze_times() RETURNS bool LANGUAGE plpgsql AS $$ BEGIN FOR i IN 1..600 LOOP PERFORM pg_stat_clear_snapshot(); /* in func */ IF (SELECT count(*) = 2 FROM pg_stat_all_tables WHERE relname IN ('analyze_time_hash', 'analyze_time_repl') AND autoanalyze_count > 0 AND total_autoanalyze_time > 0) THEN RETURN true; /* in func */ END IF; /* in func */ PERFORM pg_sleep(0.1); /* in func */ END LOOP; /* in func */ RAISE EXCEPTION 'timed out waiting for auto-analyze'; /* in func */ END; /* in func */ $$; +CREATE +SELECT wait_for_analyze_times(); + wait_for_analyze_times +------------------------ + t +(1 row) +SELECT count(*) = 2 AND bool_and(s.analyze_count = 0 AND s.autoanalyze_count > 0 AND s.total_analyze_time = 0 AND s.total_autoanalyze_time > 0 AND s.total_autoanalyze_time = q.total_autoanalyze_time) AS auto_times_match FROM gp_stat_all_tables_summary s JOIN pg_stat_all_tables q USING (relid) WHERE s.relname IN ('analyze_time_hash', 'analyze_time_repl'); + auto_times_match +------------------ + t +(1 row) +DROP FUNCTION wait_for_analyze_times(); +DROP +DROP TABLE analyze_time_hash, analyze_time_repl; +DROP +ALTER SYSTEM RESET autovacuum; +ALTER +ALTER SYSTEM RESET autovacuum_naptime; +ALTER +SELECT pg_reload_conf(); + pg_reload_conf +---------------- + t +(1 row) +RESET gp_autostats_mode; +RESET diff --git a/src/test/isolation2/expected/vacuum_ao_phase_timing.out b/src/test/isolation2/expected/vacuum_ao_phase_timing.out new file mode 100644 index 00000000000..60b2a13a89b --- /dev/null +++ b/src/test/isolation2/expected/vacuum_ao_phase_timing.out @@ -0,0 +1,87 @@ +-- Licensed to the Apache Software Foundation (ASF) under one or more +-- contributor license agreements. See the NOTICE file distributed +-- with this work for additional information regarding copyright +-- ownership. The ASF licenses this file to You under the Apache +-- License, Version 2.0 (the "License"); you may not use this file +-- except in compliance with the License. You may obtain a copy of the +-- License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +-- implied. See the License for the specific language governing +-- permissions and limitations under the License. + +-- Time is published per completed phase, even when distributed commit fails. +-- It measures consumed time; completed-vacuum counts still require post-cleanup. +-- start_matchsubs +-- m/^ERROR:.*fault name:'start_prepare'.*/ +-- s/^ERROR:.*fault name:'start_prepare'.*/ERROR: injected prepare failure/ +-- m/^ERROR:.*canceling statement due to user request.*/ +-- s/^ERROR:.*canceling statement due to user request.*/ERROR: injected prepare failure/ +-- end_matchsubs +SET gp_autostats_mode = none; +SET +CREATE TABLE ao_phase_time (a int) WITH (appendonly=true) DISTRIBUTED REPLICATED; +CREATE +INSERT INTO ao_phase_time SELECT generate_series(1, 1000); +INSERT 1000 +DELETE FROM ao_phase_time WHERE a % 2 = 0; +DELETE 500 +1: SELECT gp_inject_fault('vacuum_ao_after_compact', 'sleep', '', '', '', 1, 1, 1, dbid, current_setting('gp_session_id')::int) FROM gp_segment_configuration WHERE role = 'p' AND content > -1; + gp_inject_fault +----------------- + Success: + Success: + Success: +(3 rows) +1: SELECT gp_inject_fault('start_prepare', 'error', '', '', '', 1, 1, 0, dbid, current_setting('gp_session_id')::int) FROM gp_segment_configuration WHERE role = 'p' AND content > -1; + gp_inject_fault +----------------- + Success: + Success: + Success: +(3 rows) +1: VACUUM ao_phase_time; +ERROR: injected prepare failure +1: SELECT gp_inject_fault('start_prepare', 'reset', dbid) FROM gp_segment_configuration WHERE role = 'p' AND content > -1; + gp_inject_fault +----------------- + Success: + Success: + Success: +(3 rows) +1: SELECT gp_inject_fault('vacuum_ao_after_compact', 'reset', dbid) FROM gp_segment_configuration WHERE role = 'p' AND content > -1; + gp_inject_fault +----------------- + Success: + Success: + Success: +(3 rows) +-- At least the QE that raises the prepare error has finished its phase; +-- peers can be canceled before they finish and need not publish a time. +SELECT sum(total_vacuum_time) >= 1000 AND bool_and(vacuum_count = 0) AS aborted_phase_timed FROM gp_stat_all_tables WHERE relname = 'ao_phase_time' AND gp_segment_id > -1; + aborted_phase_timed +--------------------- + t +(1 row) +CREATE TEMP TABLE ao_time_before AS SELECT gp_segment_id AS content, total_vacuum_time FROM gp_stat_all_tables WHERE relname = 'ao_phase_time' AND gp_segment_id > -1 DISTRIBUTED BY (content); +CREATE 3 +1: VACUUM ao_phase_time; +VACUUM +SELECT bool_and(s.vacuum_count = 1 AND s.total_vacuum_time >= b.total_vacuum_time) AS completed_once FROM gp_stat_all_tables s JOIN ao_time_before b ON s.gp_segment_id = b.content WHERE s.relname = 'ao_phase_time'; + completed_once +---------------- + t +(1 row) +SELECT count(*) = 500 AS rows_preserved FROM ao_phase_time; + rows_preserved +---------------- + t +(1 row) +DROP TABLE ao_phase_time, ao_time_before; +DROP +RESET gp_autostats_mode; +RESET diff --git a/src/test/isolation2/expected/vacuum_ao_stats.out b/src/test/isolation2/expected/vacuum_ao_stats.out new file mode 100644 index 00000000000..2bb73a4726b --- /dev/null +++ b/src/test/isolation2/expected/vacuum_ao_stats.out @@ -0,0 +1,147 @@ +-- start_matchsubs +-- +-- # the segment that reports the injected error first is not deterministic +-- +-- m/^ERROR: fault triggered, fault name:'vacuum_ao_after_compact' fault type:'error' \(seg\d+ .*\)/ +-- s/^ERROR: fault triggered, fault name:'vacuum_ao_after_compact' fault type:'error' \(seg\d+ .*\)/ERROR: fault triggered, fault name:'vacuum_ao_after_compact' fault type:'error'/ +-- end_matchsubs +-- +-- The vacuum statistics of the core for append-optimized tables: the vacuum +-- and delay times of the tables and their indexes, and vacuum_interrupt_count. +-- +CREATE TABLE vacstat_ao_row (i int, v text) WITH (appendonly=true) DISTRIBUTED BY (i); +CREATE +CREATE TABLE vacstat_ao_col (i int, v text) WITH (appendonly=true, orientation=column) DISTRIBUTED BY (i); +CREATE +CREATE INDEX vacstat_ao_row_idx ON vacstat_ao_row (i); +CREATE +CREATE INDEX vacstat_ao_col_idx ON vacstat_ao_col (i); +CREATE +INSERT INTO vacstat_ao_row SELECT g, repeat('x', 100) FROM generate_series(1, 3000) g; +INSERT 3000 +INSERT INTO vacstat_ao_col SELECT g, repeat('x', 100) FROM generate_series(1, 3000) g; +INSERT 3000 +DELETE FROM vacstat_ao_row WHERE i % 2 = 0; +DELETE 1500 +DELETE FROM vacstat_ao_col WHERE i % 2 = 0; +DELETE 1500 + +-- A cost-limited vacuum sleeps, in the index passes at least, so both the +-- tables and the indexes get vacuum and delay time on every segment. +1: SET track_cost_delay_timing = on; +SET +1: SET vacuum_cost_delay = '1ms'; +SET +1: SET vacuum_cost_limit = 10; +SET +1: VACUUM vacstat_ao_row, vacstat_ao_col; +VACUUM +1: SELECT relname, count(*) FILTER (WHERE total_vacuum_time > 0) AS segments_timed, count(*) FILTER (WHERE total_vacuum_delay_time > 0) AS segments_delayed FROM gp_dist_random('pg_stat_all_tables') WHERE relname LIKE 'vacstat_ao_%' GROUP BY relname ORDER BY relname; + relname | segments_timed | segments_delayed +----------------+----------------+------------------ + vacstat_ao_col | 3 | 3 + vacstat_ao_row | 3 | 3 +(2 rows) +1: SELECT indexrelname, count(*) FILTER (WHERE total_vacuum_time > 0) AS segments_timed, count(*) FILTER (WHERE total_vacuum_delay_time > 0) AS segments_delayed FROM gp_dist_random('pg_stat_all_indexes') WHERE indexrelname LIKE 'vacstat_ao_%' GROUP BY indexrelname ORDER BY indexrelname; + indexrelname | segments_timed | segments_delayed +--------------------+----------------+------------------ + vacstat_ao_col_idx | 3 | 3 + vacstat_ao_row_idx | 3 | 3 +(2 rows) +1: RESET vacuum_cost_limit; +RESET +1: RESET vacuum_cost_delay; +RESET +1: RESET track_cost_delay_timing; +RESET + +-- A vacuum interrupted by an error. Start from zero on every instance. +1: SELECT pg_stat_reset() FROM gp_dist_random('gp_id'); + pg_stat_reset +--------------- + + + +(3 rows) +1: SELECT pg_stat_reset(); + pg_stat_reset +--------------- + +(1 row) +INSERT INTO vacstat_ao_row SELECT g, repeat('y', 100) FROM generate_series(1, 100) g; +INSERT 100 +DELETE FROM vacstat_ao_row WHERE i % 2 = 1; +DELETE 1550 + +-- Make the compact phase fail on the segments. The fault is scoped to this +-- session, so that no other backend can consume it. +1: SELECT gp_inject_fault('vacuum_ao_after_compact', 'error', '', '', '', 1, -1, 0, dbid, current_setting('gp_session_id')::int) FROM gp_segment_configuration WHERE role = 'p' AND content > -1; + gp_inject_fault +----------------- + Success: + Success: + Success: +(3 rows) +1: VACUUM vacstat_ao_row; +ERROR: fault triggered, fault name:'vacuum_ao_after_compact' fault type:'error' +1: SELECT gp_inject_fault('vacuum_ao_after_compact', 'reset', dbid) FROM gp_segment_configuration WHERE role = 'p' AND content > -1; + gp_inject_fault +----------------- + Success: + Success: + Success: +(3 rows) + +-- The phases of an append-optimized vacuum share one AOVacuumRelStats, which +-- is freed at the end of the last phase. A vacuum that fails in between used +-- to leave it behind, and the next vacuum of the relation then reused its +-- start time, so the time of everything that happened in between was added +-- to the relation's cumulative vacuum time. Let time pass. +1: SELECT pg_sleep(5); + pg_sleep +---------- + +(1 row) + +1: VACUUM vacstat_ao_row; +VACUUM + +-- The second vacuum takes milliseconds; without resetting the stats of the +-- failed one it would be credited with the five seconds slept above. +1: SELECT sum(total_vacuum_time) < 3000 AS vacuum_time_is_sane FROM gp_dist_random('pg_stat_all_tables') WHERE relname = 'vacstat_ao_row'; + vacuum_time_is_sane +--------------------- + t +(1 row) + +-- The segments that raised the error counted it; the coordinator, which only +-- dispatched the failing phase, did not. A segment may also be canceled +-- after its phase is already done, so check for "some", not for "all". +-- +-- A segment adds the count to its pending statistics when its transaction +-- ends, and flushes them when it is idle outside a transaction, which it is +-- not while its part of the failed distributed transaction waits for the +-- coordinator; the second vacuum above has ended that. Give the flush the +-- second it may wait for (PGSTAT_MIN_INTERVAL). +1: SELECT pg_sleep(2); + pg_sleep +---------- + +(1 row) +1: SELECT gp_segment_id = -1 AS coordinator, sum(vacuum_interrupt_count) > 0 AS interrupted FROM gp_stat_vacuum WHERE datname = current_database() GROUP BY 1 ORDER BY 1; + coordinator | interrupted +-------------+------------- + f | t + t | f +(2 rows) + +-- Summary counters count instance-level events, not the largest local count. +1: SELECT s.vacuum_interrupt_count = d.interrupts AND d.interrupts > 0 AND s.vacuum_failsafe_count = d.failsafes AS event_totals_match FROM gp_stat_vacuum_summary s JOIN (SELECT datid, sum(vacuum_interrupt_count) AS interrupts, sum(vacuum_failsafe_count) AS failsafes FROM gp_stat_vacuum GROUP BY datid) d USING (datid) WHERE s.datname = current_database(); + event_totals_match +-------------------- + t +(1 row) + +1: DROP TABLE vacstat_ao_row, vacstat_ao_col; +DROP +1q: ... diff --git a/src/test/isolation2/expected/vacuum_progress_column.out b/src/test/isolation2/expected/vacuum_progress_column.out index 79f7113d931..2c9d9a608e4 100644 --- a/src/test/isolation2/expected/vacuum_progress_column.out +++ b/src/test/isolation2/expected/vacuum_progress_column.out @@ -409,6 +409,12 @@ select relid::regclass as relname, phase, heap_blks_total, heap_blks_scanned, he Success: Success: (3 rows) +-- Compaction time survives replacement of the QE gang before post-cleanup. +SELECT bool_and(total_vacuum_time > 0 AND vacuum_count = 0) AS phase_time_survives FROM gp_stat_all_tables WHERE relname = 'vacuum_progress_ao_column' AND gp_segment_id > -1; + phase_time_survives +--------------------- + t +(1 row) -- now seg1's mirror is marked as down 2: SELECT content, role, preferred_role, mode, status FROM gp_segment_configuration WHERE content > -1; content | role | preferred_role | mode | status diff --git a/src/test/isolation2/expected/vacuum_progress_delay.out b/src/test/isolation2/expected/vacuum_progress_delay.out new file mode 100644 index 00000000000..bbb18e86429 --- /dev/null +++ b/src/test/isolation2/expected/vacuum_progress_delay.out @@ -0,0 +1,102 @@ +-- Licensed to the Apache Software Foundation (ASF) under one or more +-- contributor license agreements. See the NOTICE file distributed +-- with this work for additional information regarding copyright +-- ownership. The ASF licenses this file to You under the Apache +-- License, Version 2.0 (the "License"); you may not use this file +-- except in compliance with the License. You may obtain a copy of the +-- License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +-- implied. See the License for the specific language governing +-- permissions and limitations under the License. + +-- Both progress summaries sum consumed delay across workers, including +-- replicated copies. Configure utility sessions directly: timing is unsync. +CREATE TABLE progress_delay_heap (a int, padding text) WITH (autovacuum_enabled=false, fillfactor=10) DISTRIBUTED REPLICATED; +CREATE +INSERT INTO progress_delay_heap SELECT g, repeat('x', 100) FROM generate_series(1, 1000) g; +INSERT 1000 +CREATE TABLE progress_delay_ao (a int) WITH (appendonly=true) DISTRIBUTED REPLICATED; +CREATE +INSERT INTO progress_delay_ao SELECT generate_series(1, 1000); +INSERT 1000 +DELETE FROM progress_delay_ao WHERE a % 2 = 0; +DELETE 500 +0U: SET track_cost_delay_timing = on; +SET +0U: SET vacuum_cost_delay = '1ms'; +SET +0U: SET vacuum_cost_limit = 1; +SET +1U: SET track_cost_delay_timing = on; +SET +1U: SET vacuum_cost_delay = '1ms'; +SET +1U: SET vacuum_cost_limit = 1; +SET +SELECT gp_inject_fault('analyze_block', 'suspend', '', '', '', 5, 5, 0, dbid) FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); + gp_inject_fault +----------------- + Success: + Success: +(2 rows) +0U&: ANALYZE progress_delay_heap; +1U&: ANALYZE progress_delay_heap; +SELECT gp_wait_until_triggered_fault('analyze_block', 1, dbid) FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); + gp_wait_until_triggered_fault +------------------------------- + Success: + Success: +(2 rows) +SELECT s.delay_time > 0 AND s.delay_time = d.delay_time AS analyze_delay_summed FROM gp_stat_progress_analyze_summary s JOIN (SELECT relid, phase, sum(delay_time) AS delay_time FROM gp_stat_progress_analyze WHERE gp_segment_id > -1 GROUP BY relid, phase) d USING (relid, phase) WHERE s.relid = 'progress_delay_heap'::regclass; + analyze_delay_summed +---------------------- + t +(1 row) +SELECT gp_inject_fault('analyze_block', 'reset', dbid) FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); + gp_inject_fault +----------------- + Success: + Success: +(2 rows) +0U<: <... completed> +ANALYZE +1U<: <... completed> +ANALYZE +SELECT gp_inject_fault('vacuum_ao_after_compact', 'suspend', dbid) FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); + gp_inject_fault +----------------- + Success: + Success: +(2 rows) +0U&: VACUUM progress_delay_ao; +1U&: VACUUM progress_delay_ao; +SELECT gp_wait_until_triggered_fault('vacuum_ao_after_compact', 1, dbid) FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); + gp_wait_until_triggered_fault +------------------------------- + Success: + Success: +(2 rows) +SELECT s.delay_time > 0 AND s.delay_time = d.delay_time AS vacuum_delay_summed FROM gp_stat_progress_vacuum_summary s JOIN (SELECT relid, phase, sum(delay_time) AS delay_time FROM gp_stat_progress_vacuum WHERE gp_segment_id > -1 GROUP BY relid, phase) d USING (relid, phase) WHERE s.relid = 'progress_delay_ao'::regclass; + vacuum_delay_summed +--------------------- + t +(1 row) +SELECT gp_inject_fault('vacuum_ao_after_compact', 'reset', dbid) FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); + gp_inject_fault +----------------- + Success: + Success: +(2 rows) +0U<: <... completed> +VACUUM +1U<: <... completed> +VACUUM +0Uq: ... +1Uq: ... +DROP TABLE progress_delay_heap, progress_delay_ao; +DROP diff --git a/src/test/isolation2/expected/vacuum_progress_row.out b/src/test/isolation2/expected/vacuum_progress_row.out index cf7220989bc..f4e6400ced7 100644 --- a/src/test/isolation2/expected/vacuum_progress_row.out +++ b/src/test/isolation2/expected/vacuum_progress_row.out @@ -468,6 +468,12 @@ select relid::regclass as relname, phase, heap_blks_total, heap_blks_scanned, he Success: Success: (3 rows) +-- Compaction time survives replacement of the QE gang before post-cleanup. +SELECT bool_and(total_vacuum_time > 0 AND vacuum_count = 0) AS phase_time_survives FROM gp_stat_all_tables WHERE relname = 'vacuum_progress_ao_row' AND gp_segment_id > -1; + phase_time_survives +--------------------- + t +(1 row) -- now seg1's mirror is marked as down 2: SELECT content, role, preferred_role, mode, status FROM gp_segment_configuration WHERE content > -1; content | role | preferred_role | mode | status @@ -708,6 +714,12 @@ select relid::regclass as relname, phase, heap_blks_total, heap_blks_scanned, he Success: Success: (3 rows) +-- Compaction time survives replacement of the QE gang before post-cleanup. +SELECT bool_and(total_vacuum_time > 0 AND vacuum_count = 0) AS phase_time_survives FROM gp_stat_all_tables WHERE relname = 'vacuum_progress_ao_row' AND gp_segment_id > -1; + phase_time_survives +--------------------- + t +(1 row) -- now seg1's mirror is marked as down 2: SELECT content, role, preferred_role, mode, status FROM gp_segment_configuration WHERE content > -1; content | role | preferred_role | mode | status diff --git a/src/test/isolation2/isolation2_schedule b/src/test/isolation2/isolation2_schedule index 7cdf6aa9480..e362c67adde 100644 --- a/src/test/isolation2/isolation2_schedule +++ b/src/test/isolation2/isolation2_schedule @@ -156,6 +156,10 @@ test: uao/fast_analyze_row test: uao/create_index_allows_readonly_row test: reorganize_after_ao_vacuum_skip_drop truncate_after_ao_vacuum_skip_drop mark_all_aoseg_await_drop +test: vacuum_ao_stats +test: vacuum_analyze_stats +test: vacuum_ao_phase_timing +test: vacuum_progress_delay # below test(s) inject faults so each of them need to be in a separate group test: segwalrep/master_wal_switch diff --git a/src/test/isolation2/sql/vacuum_analyze_stats.sql b/src/test/isolation2/sql/vacuum_analyze_stats.sql new file mode 100644 index 00000000000..bb7c6e9c245 --- /dev/null +++ b/src/test/isolation2/sql/vacuum_analyze_stats.sql @@ -0,0 +1,73 @@ +-- Licensed to the Apache Software Foundation (ASF) under one or more +-- contributor license agreements. See the NOTICE file distributed +-- with this work for additional information regarding copyright +-- ownership. The ASF licenses this file to You under the Apache +-- License, Version 2.0 (the "License"); you may not use this file +-- except in compliance with the License. You may obtain a copy of the +-- License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +-- implied. See the License for the specific language governing +-- permissions and limitations under the License. + +-- Counts and elapsed times must use the same coordinator ANALYZE record. +-- QE sampling records auto-analyze as manual ANALYZE. +SET gp_autostats_mode = none; +CREATE TABLE analyze_time_hash (a int) + WITH (autovacuum_enabled = false) DISTRIBUTED BY (a); +CREATE TABLE analyze_time_repl (a int) + WITH (autovacuum_enabled = false) DISTRIBUTED REPLICATED; +INSERT INTO analyze_time_hash SELECT generate_series(1, 50000); +INSERT INTO analyze_time_repl SELECT generate_series(1, 50000); +ANALYZE analyze_time_hash; +ANALYZE analyze_time_repl; +SELECT count(*) = 2 AND bool_and(s.analyze_count = 1 AND s.autoanalyze_count = 0 + AND s.total_analyze_time > 0 AND s.total_autoanalyze_time = 0 + AND s.total_analyze_time = q.total_analyze_time) AS manual_times_match + FROM gp_stat_all_tables_summary s JOIN pg_stat_all_tables q USING (relid) + WHERE s.relname IN ('analyze_time_hash', 'analyze_time_repl'); + +-- Start a fresh interval, then let an actual coordinator autovacuum worker +-- analyze both tables. No explicit ANALYZE may contribute to this interval. +SELECT pg_stat_reset_single_table_counters('analyze_time_hash'::regclass); +SELECT pg_stat_reset_single_table_counters('analyze_time_repl'::regclass); +ALTER TABLE analyze_time_hash SET (autovacuum_enabled = true, + autovacuum_analyze_threshold = 100, autovacuum_analyze_scale_factor = 0); +ALTER TABLE analyze_time_repl SET (autovacuum_enabled = true, + autovacuum_analyze_threshold = 100, autovacuum_analyze_scale_factor = 0); +ALTER SYSTEM SET autovacuum = on; +ALTER SYSTEM SET autovacuum_naptime = '1s'; +SELECT pg_reload_conf(); +INSERT INTO analyze_time_hash SELECT generate_series(50001, 60000); +INSERT INTO analyze_time_repl SELECT generate_series(50001, 60000); +SELECT gp_stat_force_next_flush(); +CREATE FUNCTION wait_for_analyze_times() RETURNS bool LANGUAGE plpgsql AS $$ +BEGIN + FOR i IN 1..600 LOOP + PERFORM pg_stat_clear_snapshot(); /* in func */ + IF (SELECT count(*) = 2 FROM pg_stat_all_tables + WHERE relname IN ('analyze_time_hash', 'analyze_time_repl') + AND autoanalyze_count > 0 AND total_autoanalyze_time > 0) THEN + RETURN true; /* in func */ + END IF; /* in func */ + PERFORM pg_sleep(0.1); /* in func */ + END LOOP; /* in func */ + RAISE EXCEPTION 'timed out waiting for auto-analyze'; /* in func */ +END; /* in func */ +$$; +SELECT wait_for_analyze_times(); +SELECT count(*) = 2 AND bool_and(s.analyze_count = 0 AND s.autoanalyze_count > 0 + AND s.total_analyze_time = 0 AND s.total_autoanalyze_time > 0 + AND s.total_autoanalyze_time = q.total_autoanalyze_time) AS auto_times_match + FROM gp_stat_all_tables_summary s JOIN pg_stat_all_tables q USING (relid) + WHERE s.relname IN ('analyze_time_hash', 'analyze_time_repl'); +DROP FUNCTION wait_for_analyze_times(); +DROP TABLE analyze_time_hash, analyze_time_repl; +ALTER SYSTEM RESET autovacuum; +ALTER SYSTEM RESET autovacuum_naptime; +SELECT pg_reload_conf(); +RESET gp_autostats_mode; diff --git a/src/test/isolation2/sql/vacuum_ao_phase_timing.sql b/src/test/isolation2/sql/vacuum_ao_phase_timing.sql new file mode 100644 index 00000000000..42d01cf5605 --- /dev/null +++ b/src/test/isolation2/sql/vacuum_ao_phase_timing.sql @@ -0,0 +1,55 @@ +-- Licensed to the Apache Software Foundation (ASF) under one or more +-- contributor license agreements. See the NOTICE file distributed +-- with this work for additional information regarding copyright +-- ownership. The ASF licenses this file to You under the Apache +-- License, Version 2.0 (the "License"); you may not use this file +-- except in compliance with the License. You may obtain a copy of the +-- License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +-- implied. See the License for the specific language governing +-- permissions and limitations under the License. + +-- Time is published per completed phase, even when distributed commit fails. +-- It measures consumed time; completed-vacuum counts still require post-cleanup. +-- start_matchsubs +-- m/^ERROR:.*fault name:'start_prepare'.*/ +-- s/^ERROR:.*fault name:'start_prepare'.*/ERROR: injected prepare failure/ +-- m/^ERROR:.*canceling statement due to user request.*/ +-- s/^ERROR:.*canceling statement due to user request.*/ERROR: injected prepare failure/ +-- end_matchsubs +SET gp_autostats_mode = none; +CREATE TABLE ao_phase_time (a int) WITH (appendonly=true) + DISTRIBUTED REPLICATED; +INSERT INTO ao_phase_time SELECT generate_series(1, 1000); +DELETE FROM ao_phase_time WHERE a % 2 = 0; +1: SELECT gp_inject_fault('vacuum_ao_after_compact', 'sleep', '', '', '', 1, 1, 1, + dbid, current_setting('gp_session_id')::int) + FROM gp_segment_configuration WHERE role = 'p' AND content > -1; +1: SELECT gp_inject_fault('start_prepare', 'error', '', '', '', 1, 1, 0, + dbid, current_setting('gp_session_id')::int) + FROM gp_segment_configuration WHERE role = 'p' AND content > -1; +1: VACUUM ao_phase_time; +1: SELECT gp_inject_fault('start_prepare', 'reset', dbid) + FROM gp_segment_configuration WHERE role = 'p' AND content > -1; +1: SELECT gp_inject_fault('vacuum_ao_after_compact', 'reset', dbid) + FROM gp_segment_configuration WHERE role = 'p' AND content > -1; +-- At least the QE that raises the prepare error has finished its phase; +-- peers can be canceled before they finish and need not publish a time. +SELECT sum(total_vacuum_time) >= 1000 AND bool_and(vacuum_count = 0) AS aborted_phase_timed + FROM gp_stat_all_tables WHERE relname = 'ao_phase_time' AND gp_segment_id > -1; +CREATE TEMP TABLE ao_time_before AS SELECT gp_segment_id AS content, total_vacuum_time + FROM gp_stat_all_tables WHERE relname = 'ao_phase_time' AND gp_segment_id > -1 + DISTRIBUTED BY (content); +1: VACUUM ao_phase_time; +SELECT bool_and(s.vacuum_count = 1 AND s.total_vacuum_time >= b.total_vacuum_time) + AS completed_once + FROM gp_stat_all_tables s JOIN ao_time_before b ON s.gp_segment_id = b.content + WHERE s.relname = 'ao_phase_time'; +SELECT count(*) = 500 AS rows_preserved FROM ao_phase_time; +DROP TABLE ao_phase_time, ao_time_before; +RESET gp_autostats_mode; diff --git a/src/test/isolation2/sql/vacuum_ao_stats.sql b/src/test/isolation2/sql/vacuum_ao_stats.sql new file mode 100644 index 00000000000..99397a5819f --- /dev/null +++ b/src/test/isolation2/sql/vacuum_ao_stats.sql @@ -0,0 +1,93 @@ +-- start_matchsubs +-- +-- # the segment that reports the injected error first is not deterministic +-- +-- m/^ERROR: fault triggered, fault name:'vacuum_ao_after_compact' fault type:'error' \(seg\d+ .*\)/ +-- s/^ERROR: fault triggered, fault name:'vacuum_ao_after_compact' fault type:'error' \(seg\d+ .*\)/ERROR: fault triggered, fault name:'vacuum_ao_after_compact' fault type:'error'/ +-- end_matchsubs +-- +-- The vacuum statistics of the core for append-optimized tables: the vacuum +-- and delay times of the tables and their indexes, and vacuum_interrupt_count. +-- +CREATE TABLE vacstat_ao_row (i int, v text) WITH (appendonly=true) DISTRIBUTED BY (i); +CREATE TABLE vacstat_ao_col (i int, v text) WITH (appendonly=true, orientation=column) DISTRIBUTED BY (i); +CREATE INDEX vacstat_ao_row_idx ON vacstat_ao_row (i); +CREATE INDEX vacstat_ao_col_idx ON vacstat_ao_col (i); +INSERT INTO vacstat_ao_row SELECT g, repeat('x', 100) FROM generate_series(1, 3000) g; +INSERT INTO vacstat_ao_col SELECT g, repeat('x', 100) FROM generate_series(1, 3000) g; +DELETE FROM vacstat_ao_row WHERE i % 2 = 0; +DELETE FROM vacstat_ao_col WHERE i % 2 = 0; + +-- A cost-limited vacuum sleeps, in the index passes at least, so both the +-- tables and the indexes get vacuum and delay time on every segment. +1: SET track_cost_delay_timing = on; +1: SET vacuum_cost_delay = '1ms'; +1: SET vacuum_cost_limit = 10; +1: VACUUM vacstat_ao_row, vacstat_ao_col; +1: SELECT relname, count(*) FILTER (WHERE total_vacuum_time > 0) AS segments_timed, + count(*) FILTER (WHERE total_vacuum_delay_time > 0) AS segments_delayed + FROM gp_dist_random('pg_stat_all_tables') + WHERE relname LIKE 'vacstat_ao_%' GROUP BY relname ORDER BY relname; +1: SELECT indexrelname, count(*) FILTER (WHERE total_vacuum_time > 0) AS segments_timed, + count(*) FILTER (WHERE total_vacuum_delay_time > 0) AS segments_delayed + FROM gp_dist_random('pg_stat_all_indexes') + WHERE indexrelname LIKE 'vacstat_ao_%' GROUP BY indexrelname ORDER BY indexrelname; +1: RESET vacuum_cost_limit; +1: RESET vacuum_cost_delay; +1: RESET track_cost_delay_timing; + +-- A vacuum interrupted by an error. Start from zero on every instance. +1: SELECT pg_stat_reset() FROM gp_dist_random('gp_id'); +1: SELECT pg_stat_reset(); +INSERT INTO vacstat_ao_row SELECT g, repeat('y', 100) FROM generate_series(1, 100) g; +DELETE FROM vacstat_ao_row WHERE i % 2 = 1; + +-- Make the compact phase fail on the segments. The fault is scoped to this +-- session, so that no other backend can consume it. +1: SELECT gp_inject_fault('vacuum_ao_after_compact', 'error', '', '', '', 1, -1, 0, dbid, + current_setting('gp_session_id')::int) + FROM gp_segment_configuration WHERE role = 'p' AND content > -1; +1: VACUUM vacstat_ao_row; +1: SELECT gp_inject_fault('vacuum_ao_after_compact', 'reset', dbid) + FROM gp_segment_configuration WHERE role = 'p' AND content > -1; + +-- The phases of an append-optimized vacuum share one AOVacuumRelStats, which +-- is freed at the end of the last phase. A vacuum that fails in between used +-- to leave it behind, and the next vacuum of the relation then reused its +-- start time, so the time of everything that happened in between was added +-- to the relation's cumulative vacuum time. Let time pass. +1: SELECT pg_sleep(5); + +1: VACUUM vacstat_ao_row; + +-- The second vacuum takes milliseconds; without resetting the stats of the +-- failed one it would be credited with the five seconds slept above. +1: SELECT sum(total_vacuum_time) < 3000 AS vacuum_time_is_sane + FROM gp_dist_random('pg_stat_all_tables') WHERE relname = 'vacstat_ao_row'; + +-- The segments that raised the error counted it; the coordinator, which only +-- dispatched the failing phase, did not. A segment may also be canceled +-- after its phase is already done, so check for "some", not for "all". +-- +-- A segment adds the count to its pending statistics when its transaction +-- ends, and flushes them when it is idle outside a transaction, which it is +-- not while its part of the failed distributed transaction waits for the +-- coordinator; the second vacuum above has ended that. Give the flush the +-- second it may wait for (PGSTAT_MIN_INTERVAL). +1: SELECT pg_sleep(2); +1: SELECT gp_segment_id = -1 AS coordinator, + sum(vacuum_interrupt_count) > 0 AS interrupted + FROM gp_stat_vacuum WHERE datname = current_database() + GROUP BY 1 ORDER BY 1; + +-- Summary counters count instance-level events, not the largest local count. +1: SELECT s.vacuum_interrupt_count = d.interrupts AND d.interrupts > 0 + AND s.vacuum_failsafe_count = d.failsafes AS event_totals_match + FROM gp_stat_vacuum_summary s + JOIN (SELECT datid, sum(vacuum_interrupt_count) AS interrupts, + sum(vacuum_failsafe_count) AS failsafes + FROM gp_stat_vacuum GROUP BY datid) d USING (datid) + WHERE s.datname = current_database(); + +1: DROP TABLE vacstat_ao_row, vacstat_ao_col; +1q: diff --git a/src/test/isolation2/sql/vacuum_progress_column.sql b/src/test/isolation2/sql/vacuum_progress_column.sql index 56e6c04da56..f7f6ec1fcbd 100644 --- a/src/test/isolation2/sql/vacuum_progress_column.sql +++ b/src/test/isolation2/sql/vacuum_progress_column.sql @@ -173,6 +173,9 @@ select relid::regclass as relname, phase, heap_blks_total, heap_blks_scanned, he -- Also all segments should reach to the same "vacuum_worker_changed" point -- due to FTS version being changed. 2: SELECT gp_wait_until_triggered_fault('vacuum_worker_changed', 1, dbid) FROM gp_segment_configuration WHERE content > -1 AND role = 'p'; +-- Compaction time survives replacement of the QE gang before post-cleanup. +SELECT bool_and(total_vacuum_time > 0 AND vacuum_count = 0) AS phase_time_survives + FROM gp_stat_all_tables WHERE relname = 'vacuum_progress_ao_column' AND gp_segment_id > -1; -- now seg1's mirror is marked as down 2: SELECT content, role, preferred_role, mode, status FROM gp_segment_configuration WHERE content > -1; diff --git a/src/test/isolation2/sql/vacuum_progress_delay.sql b/src/test/isolation2/sql/vacuum_progress_delay.sql new file mode 100644 index 00000000000..ed0034ceff1 --- /dev/null +++ b/src/test/isolation2/sql/vacuum_progress_delay.sql @@ -0,0 +1,67 @@ +-- Licensed to the Apache Software Foundation (ASF) under one or more +-- contributor license agreements. See the NOTICE file distributed +-- with this work for additional information regarding copyright +-- ownership. The ASF licenses this file to You under the Apache +-- License, Version 2.0 (the "License"); you may not use this file +-- except in compliance with the License. You may obtain a copy of the +-- License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +-- implied. See the License for the specific language governing +-- permissions and limitations under the License. + +-- Both progress summaries sum consumed delay across workers, including +-- replicated copies. Configure utility sessions directly: timing is unsync. +CREATE TABLE progress_delay_heap (a int, padding text) + WITH (autovacuum_enabled=false, fillfactor=10) DISTRIBUTED REPLICATED; +INSERT INTO progress_delay_heap SELECT g, repeat('x', 100) + FROM generate_series(1, 1000) g; +CREATE TABLE progress_delay_ao (a int) WITH (appendonly=true) + DISTRIBUTED REPLICATED; +INSERT INTO progress_delay_ao SELECT generate_series(1, 1000); +DELETE FROM progress_delay_ao WHERE a % 2 = 0; +0U: SET track_cost_delay_timing = on; +0U: SET vacuum_cost_delay = '1ms'; +0U: SET vacuum_cost_limit = 1; +1U: SET track_cost_delay_timing = on; +1U: SET vacuum_cost_delay = '1ms'; +1U: SET vacuum_cost_limit = 1; +SELECT gp_inject_fault('analyze_block', 'suspend', '', '', '', 5, 5, 0, dbid) + FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); +0U&: ANALYZE progress_delay_heap; +1U&: ANALYZE progress_delay_heap; +SELECT gp_wait_until_triggered_fault('analyze_block', 1, dbid) + FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); +SELECT s.delay_time > 0 AND s.delay_time = d.delay_time AS analyze_delay_summed + FROM gp_stat_progress_analyze_summary s + JOIN (SELECT relid, phase, sum(delay_time) AS delay_time + FROM gp_stat_progress_analyze WHERE gp_segment_id > -1 + GROUP BY relid, phase) d USING (relid, phase) + WHERE s.relid = 'progress_delay_heap'::regclass; +SELECT gp_inject_fault('analyze_block', 'reset', dbid) + FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); +0U<: +1U<: +SELECT gp_inject_fault('vacuum_ao_after_compact', 'suspend', dbid) + FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); +0U&: VACUUM progress_delay_ao; +1U&: VACUUM progress_delay_ao; +SELECT gp_wait_until_triggered_fault('vacuum_ao_after_compact', 1, dbid) + FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); +SELECT s.delay_time > 0 AND s.delay_time = d.delay_time AS vacuum_delay_summed + FROM gp_stat_progress_vacuum_summary s + JOIN (SELECT relid, phase, sum(delay_time) AS delay_time + FROM gp_stat_progress_vacuum WHERE gp_segment_id > -1 + GROUP BY relid, phase) d USING (relid, phase) + WHERE s.relid = 'progress_delay_ao'::regclass; +SELECT gp_inject_fault('vacuum_ao_after_compact', 'reset', dbid) + FROM gp_segment_configuration WHERE role = 'p' AND content IN (0, 1); +0U<: +1U<: +0Uq: +1Uq: +DROP TABLE progress_delay_heap, progress_delay_ao; diff --git a/src/test/isolation2/sql/vacuum_progress_row.sql b/src/test/isolation2/sql/vacuum_progress_row.sql index a7b514bfccd..a2cc08797f2 100644 --- a/src/test/isolation2/sql/vacuum_progress_row.sql +++ b/src/test/isolation2/sql/vacuum_progress_row.sql @@ -179,6 +179,9 @@ select relid::regclass as relname, phase, heap_blks_total, heap_blks_scanned, he -- Also all segments should reach to the same "vacuum_worker_changed" point -- due to FTS version being changed. 2: SELECT gp_wait_until_triggered_fault('vacuum_worker_changed', 1, dbid) FROM gp_segment_configuration WHERE content > -1 AND role = 'p'; +-- Compaction time survives replacement of the QE gang before post-cleanup. +SELECT bool_and(total_vacuum_time > 0 AND vacuum_count = 0) AS phase_time_survives + FROM gp_stat_all_tables WHERE relname = 'vacuum_progress_ao_row' AND gp_segment_id > -1; -- now seg1's mirror is marked as down 2: SELECT content, role, preferred_role, mode, status FROM gp_segment_configuration WHERE content > -1; @@ -269,6 +272,9 @@ select relid::regclass as relname, phase, heap_blks_total, heap_blks_scanned, he -- Also all segments should reach to the same "vacuum_worker_changed" point -- due to FTS version being changed. 2: SELECT gp_wait_until_triggered_fault('vacuum_worker_changed', 1, dbid) FROM gp_segment_configuration WHERE content > -1 AND role = 'p'; +-- Compaction time survives replacement of the QE gang before post-cleanup. +SELECT bool_and(total_vacuum_time > 0 AND vacuum_count = 0) AS phase_time_survives + FROM gp_stat_all_tables WHERE relname = 'vacuum_progress_ao_row' AND gp_segment_id > -1; -- now seg1's mirror is marked as down 2: SELECT content, role, preferred_role, mode, status FROM gp_segment_configuration WHERE content > -1; diff --git a/src/test/modules/test_misc/Makefile b/src/test/modules/test_misc/Makefile index b71f06b0c32..b69beda44b7 100644 --- a/src/test/modules/test_misc/Makefile +++ b/src/test/modules/test_misc/Makefile @@ -14,3 +14,8 @@ top_builddir = ../../../.. include $(top_builddir)/src/Makefile.global include $(top_srcdir)/contrib/contrib-global.mk endif + +# Native maintenance statistics coverage for the ic-tap CI job. +.PHONY: installcheck-vacuum +installcheck-vacuum: PROVE_TESTS = t/016_index_vacuum_time.pl t/017_vacuum_failsafe.pl t/018_vacuum_interrupts.pl +installcheck-vacuum: installcheck diff --git a/src/test/modules/test_misc/meson.build b/src/test/modules/test_misc/meson.build index 82166f03ce0..88249df7be2 100644 --- a/src/test/modules/test_misc/meson.build +++ b/src/test/modules/test_misc/meson.build @@ -16,6 +16,9 @@ tests += { 't/002_tablespace.pl', 't/003_check_guc.pl', 't/004_io_direct.pl', + 't/016_index_vacuum_time.pl', + 't/017_vacuum_failsafe.pl', + 't/018_vacuum_interrupts.pl', 't/019_resqueue_stats_restart.pl', 't/020_custom_stats_restart.pl', 't/029_vacuum_resource_verbose.pl', diff --git a/src/test/modules/test_misc/t/016_index_vacuum_time.pl b/src/test/modules/test_misc/t/016_index_vacuum_time.pl new file mode 100644 index 00000000000..4eb02ab2517 --- /dev/null +++ b/src/test/modules/test_misc/t/016_index_vacuum_time.pl @@ -0,0 +1,80 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Test the total_vacuum_time counter of pg_stat_all_indexes: the time vacuum +# spent processing each index, accumulated over bulkdelete and cleanup passes, +# mirroring the table-level counter in pg_stat_all_tables. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $node = PostgreSQL::Test::Cluster->new('main'); +$node->init; +$node->append_conf( + 'postgresql.conf', qq[ +autovacuum = off +track_cost_delay_timing = on +]); +$node->start; + +# The index has to span enough pages for its vacuum passes to exceed +# vacuum_cost_limit on buffer hits alone (its pages are still dirty from the +# load, so dirtying them costs nothing). Scale the row count with the block +# size, so that builds with larger blocks (32kB in Cloudberry) keep the page +# count of the default 8kB. +my $nrows = 100000 * + ($node->safe_psql('postgres', 'SHOW block_size') / 8192); + +# Enough rows that the bulkdelete pass over the index takes measurable time; +# a small vacuum_cost_delay adds deterministic delay time on fast machines. +$node->safe_psql( + 'postgres', qq[ +CREATE TABLE vactime_t (id int PRIMARY KEY, v text) WITH (autovacuum_enabled = off); +INSERT INTO vactime_t SELECT g, repeat('x', 10) FROM generate_series(1, $nrows) g; +DELETE FROM vactime_t WHERE id % 2 = 0; +]); +$node->safe_psql( + 'postgres', qq[ +SET vacuum_cost_delay = '1ms'; +SET vacuum_cost_limit = 200; +VACUUM vactime_t; +]); + +# The upper bound guards against garbage such as an epoch-based elapsed time +# leaking into the counter. +is( $node->safe_psql( + 'postgres', qq[ +SELECT total_vacuum_time > 0 AND total_vacuum_time < 600000 + FROM pg_stat_all_indexes WHERE indexrelname = 'vactime_t_pkey']), + 't', + 'total_vacuum_time advanced sanely for the index in pg_stat_all_indexes'); + +is( $node->safe_psql( + 'postgres', qq[ +SELECT total_vacuum_delay_time > 0 AND total_vacuum_delay_time <= total_vacuum_time + FROM pg_stat_all_indexes WHERE indexrelname = 'vactime_t_pkey']), + 't', + 'total_vacuum_delay_time advanced and not above total_vacuum_time'); + +is( $node->safe_psql( + 'postgres', qq[ +SELECT total_autovacuum_time = 0 FROM pg_stat_all_indexes + WHERE indexrelname = 'vactime_t_pkey']), + 't', + 'manual vacuum did not count into total_autovacuum_time'); + +# The same run must have accumulated into the database-wide totals. +is( $node->safe_psql( + 'postgres', qq[ +SELECT total_vacuum_time > 0 AND total_vacuum_time < 600000 + AND total_vacuum_delay_time > 0 + AND total_vacuum_delay_time <= total_vacuum_time + FROM pg_stat_vacuum WHERE datname = current_database()]), + 't', + 'database-wide vacuum times advanced sanely in pg_stat_vacuum'); + +$node->stop; + +done_testing(); diff --git a/src/test/modules/test_misc/t/017_vacuum_failsafe.pl b/src/test/modules/test_misc/t/017_vacuum_failsafe.pl new file mode 100644 index 00000000000..9332c250477 --- /dev/null +++ b/src/test/modules/test_misc/t/017_vacuum_failsafe.pl @@ -0,0 +1,71 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Test that vacuums entering the wraparound failsafe mode are counted in +# pg_stat_all_tables.vacuum_failsafe_count and aggregated per database in +# pg_stat_vacuum.vacuum_failsafe_count. +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $node = PostgreSQL::Test::Cluster->new('main'); +$node->init; +# The failsafe cutoff is clamped to 1.05 * autovacuum_freeze_max_age, so use +# the minimum allowed value to keep the number of XIDs to burn small. +$node->append_conf( + 'postgresql.conf', qq[ +autovacuum = off +autovacuum_freeze_max_age = 100000 +]); +$node->start; + +$node->safe_psql( + 'postgres', qq[ + CREATE TABLE tab_failsafe (i int); + INSERT INTO tab_failsafe SELECT generate_series(1, 100); +]); + +# A vacuum without failsafe pressure must not bump the counter. +$node->safe_psql('postgres', 'VACUUM tab_failsafe;'); +my $count = $node->safe_psql('postgres', + q[SELECT vacuum_failsafe_count FROM pg_stat_all_tables WHERE relname = 'tab_failsafe';] +); +is($count, '0', 'normal vacuum does not count as failsafe'); + +# Age the table past 1.05 * autovacuum_freeze_max_age: burn XIDs with +# aborted subtransactions (each aborted subxact consumes an assigned XID). +$node->safe_psql( + 'postgres', qq[ + CREATE TABLE burn_xids (i int); + DO \$\$ + BEGIN + FOR i IN 1..110000 LOOP + BEGIN + INSERT INTO burn_xids VALUES (1); + RAISE EXCEPTION 'burn'; + EXCEPTION WHEN OTHERS THEN + END; + END LOOP; + END \$\$; +]); + +# vacuum_failsafe_age = 0 makes the (clamped) cutoff kick in immediately. +$node->safe_psql( + 'postgres', qq[ + SET vacuum_failsafe_age = 0; + SET vacuum_multixact_failsafe_age = 0; + VACUUM tab_failsafe; +]); + +$count = $node->safe_psql('postgres', + q[SELECT vacuum_failsafe_count FROM pg_stat_all_tables WHERE relname = 'tab_failsafe';] +); +is($count, '1', 'failsafe vacuum counted in pg_stat_all_tables'); + +my $db_count = $node->safe_psql('postgres', + q[SELECT vacuum_failsafe_count FROM pg_stat_vacuum WHERE datname = 'postgres';] +); +is($db_count, '1', 'failsafe vacuum counted in pg_stat_vacuum'); + +done_testing(); diff --git a/src/test/modules/test_misc/t/018_vacuum_interrupts.pl b/src/test/modules/test_misc/t/018_vacuum_interrupts.pl new file mode 100644 index 00000000000..f1cb11462ac --- /dev/null +++ b/src/test/modules/test_misc/t/018_vacuum_interrupts.pl @@ -0,0 +1,71 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Test the vacuum_interrupt_count counter of pg_stat_vacuum. +# +# vacuum_interrupt_count records how many times a vacuum in the database was +# interrupted by an error. We provoke that by starting a vacuum that sleeps +# at its cost-based delay points and canceling it, with pg_cancel_backend(), +# while it is still running. + +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $node = PostgreSQL::Test::Cluster->new('main'); +$node->init; +$node->append_conf( + 'postgresql.conf', qq[ +autovacuum = off +]); +$node->start; + +# fillfactor = 10 spreads the rows over many pages so the vacuum hits enough +# cost-delay points to stay running until we cancel it. +$node->safe_psql( + 'postgres', qq[ +CREATE TABLE vacstat_int (id int) WITH (autovacuum_enabled = off, fillfactor = 10); +INSERT INTO vacstat_int SELECT generate_series(1, 1000); +DELETE FROM vacstat_int; +]); + +# Start a vacuum that sleeps at every cost-delay point, in the background. The +# \echo lets query_until() return as soon as the VACUUM has been launched. +my $appname = 'vacuum_interrupt_test'; +my $vac = $node->background_psql('postgres', on_error_stop => 0); +$vac->query_until( + qr/start/, qq[ +SET application_name = '$appname'; +SET vacuum_cost_delay = '100ms'; +SET vacuum_cost_limit = 1; +\\echo start +VACUUM vacstat_int; +]); + +# Wait until the vacuum is actually running, then cancel it. +$node->poll_query_until( + 'postgres', qq[ +SELECT count(*) = 1 FROM pg_stat_activity + WHERE application_name = '$appname' AND query LIKE 'VACUUM%' AND state = 'active']) + or die "timed out waiting for the vacuum to start"; + +my $cancelled = $node->safe_psql( + 'postgres', qq[ +SELECT pg_cancel_backend(pid) FROM pg_stat_activity + WHERE application_name = '$appname' AND query LIKE 'VACUUM%']); +is($cancelled, 't', 'canceled the running vacuum'); + +$vac->quit; +like($vac->{stderr}, qr/canceling statement due to user request/, + 'vacuum canceled by user request'); + +is( $node->safe_psql( + 'postgres', qq[ +SELECT vacuum_interrupt_count > 0 FROM pg_stat_vacuum WHERE datname = current_database()]), + 't', + 'vacuum_interrupt_count advanced in pg_stat_vacuum'); + +$node->stop; + +done_testing(); diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index 614ffea1784..94c1f53b4c9 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -1798,7 +1798,16 @@ pg_stat_all_tables| SELECT c.oid AS relid, pg_stat_get_vacuum_count(c.oid) AS vacuum_count, pg_stat_get_autovacuum_count(c.oid) AS autovacuum_count, pg_stat_get_analyze_count(c.oid) AS analyze_count, - pg_stat_get_autoanalyze_count(c.oid) AS autoanalyze_count + pg_stat_get_autoanalyze_count(c.oid) AS autoanalyze_count, + pg_stat_get_total_vacuum_time(c.oid) AS total_vacuum_time, + pg_stat_get_total_autovacuum_time(c.oid) AS total_autovacuum_time, + pg_stat_get_total_analyze_time(c.oid) AS total_analyze_time, + pg_stat_get_total_autoanalyze_time(c.oid) AS total_autoanalyze_time, + pg_stat_get_total_vacuum_delay_time(c.oid) AS total_vacuum_delay_time, + pg_stat_get_total_autovacuum_delay_time(c.oid) AS total_autovacuum_delay_time, + pg_stat_get_vacuum_failsafe_count(c.oid) AS vacuum_failsafe_count, + pg_stat_get_visible_page_marks_cleared(c.oid) AS visible_page_marks_cleared, + pg_stat_get_frozen_page_marks_cleared(c.oid) AS frozen_page_marks_cleared FROM ((pg_class c LEFT JOIN pg_index i ON ((c.oid = i.indrelid))) LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace))) @@ -1916,7 +1925,8 @@ pg_stat_progress_analyze| SELECT d.gp_segment_id, s.param5 AS ext_stats_computed, s.param6 AS child_tables_total, s.param7 AS child_tables_done, - (s.param8)::oid AS current_child_table_relid + (s.param8)::oid AS current_child_table_relid, + ((s.param9)::double precision / (1000000)::double precision) AS delay_time FROM (pg_stat_get_progress_info('ANALYZE'::text) s(pid, datid, relid, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11, param12, param13, param14, param15, param16, param17, param18, param19, param20) LEFT JOIN pg_database d ON ((s.datid = d.oid))); pg_stat_progress_basebackup| SELECT gp_execution_segment() AS gp_segment_id, @@ -2043,7 +2053,8 @@ pg_stat_progress_vacuum| SELECT d.gp_segment_id, s.param4 AS heap_blks_vacuumed, s.param5 AS index_vacuum_count, s.param6 AS max_dead_tuples, - s.param7 AS num_dead_tuples + s.param7 AS num_dead_tuples, + ((s.param8)::double precision / (1000000)::double precision) AS delay_time FROM (pg_stat_get_progress_info('VACUUM'::text) s(pid, datid, relid, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11, param12, param13, param14, param15, param16, param17, param18, param19, param20) LEFT JOIN pg_database d ON ((s.datid = d.oid))); pg_stat_recovery_prefetch| SELECT stats_reset, @@ -2168,7 +2179,16 @@ pg_stat_sys_tables| SELECT relid, vacuum_count, autovacuum_count, analyze_count, - autoanalyze_count + autoanalyze_count, + total_vacuum_time, + total_autovacuum_time, + total_analyze_time, + total_autoanalyze_time, + total_vacuum_delay_time, + total_autovacuum_delay_time, + vacuum_failsafe_count, + visible_page_marks_cleared, + frozen_page_marks_cleared FROM pg_stat_all_tables WHERE ((schemaname = ANY (ARRAY['pg_catalog'::name, 'information_schema'::name])) OR (schemaname ~ '^pg_toast'::text)); pg_stat_user_functions| SELECT p.oid AS funcid, @@ -2216,9 +2236,33 @@ pg_stat_user_tables| SELECT relid, vacuum_count, autovacuum_count, analyze_count, - autoanalyze_count + autoanalyze_count, + total_vacuum_time, + total_autovacuum_time, + total_analyze_time, + total_autoanalyze_time, + total_vacuum_delay_time, + total_autovacuum_delay_time, + vacuum_failsafe_count, + visible_page_marks_cleared, + frozen_page_marks_cleared FROM pg_stat_all_tables WHERE ((schemaname <> ALL (ARRAY['pg_catalog'::name, 'information_schema'::name])) AND (schemaname !~ '^pg_toast'::text)); +pg_stat_vacuum| SELECT d.oid AS datid, + d.datname, + pg_stat_get_db_total_vacuum_time(d.oid) AS total_vacuum_time, + pg_stat_get_db_total_autovacuum_time(d.oid) AS total_autovacuum_time, + pg_stat_get_db_total_vacuum_delay_time(d.oid) AS total_vacuum_delay_time, + pg_stat_get_db_total_autovacuum_delay_time(d.oid) AS total_autovacuum_delay_time, + pg_stat_get_db_vacuum_failsafe_count(d.oid) AS vacuum_failsafe_count, + pg_stat_get_db_vacuum_interrupt_count(d.oid) AS vacuum_interrupt_count, + pg_stat_get_db_stat_reset_time(d.oid) AS stats_reset + FROM ( SELECT 0 AS oid, + NULL::name AS datname + UNION ALL + SELECT pg_database.oid, + pg_database.datname + FROM pg_database) d; pg_stat_wal| SELECT wal_records, wal_fpi, wal_bytes, diff --git a/src/test/regress/expected/vacuum_stats.out b/src/test/regress/expected/vacuum_stats.out index 573f7527fde..df504318eeb 100644 --- a/src/test/regress/expected/vacuum_stats.out +++ b/src/test/regress/expected/vacuum_stats.out @@ -28,4 +28,4 @@ AND relallvisible = t (1 row) -DROP TABLE vacstat_test +DROP TABLE vacstat_test; diff --git a/src/test/regress/sql/vacuum_stats.sql b/src/test/regress/sql/vacuum_stats.sql index 45a9b6466c4..2a63e3b7388 100644 --- a/src/test/regress/sql/vacuum_stats.sql +++ b/src/test/regress/sql/vacuum_stats.sql @@ -19,4 +19,5 @@ AND relallvisible = (SELECT SUM(relallvisible) FROM gp_dist_random('pg_class') WHERE oid='vacstat_test'::regclass); -DROP TABLE vacstat_test +DROP TABLE vacstat_test; + From 01941a0853ccf40f4a48eebc453d196b6c8da647 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Fri, 9 Oct 2026 20:48:37 +0300 Subject: [PATCH 14/20] Test native VACUUM cluster timing without the extension Move cluster timing, index-summary cardinality, and track_cost_delay_timing scope checks from the extension regression into the core vacuum_stats test. Cover distributed and replicated tables, and explicitly flush database statistics before checking their timing aggregate. --- src/test/regress/expected/vacuum_stats.out | 86 ++++++++++++++++++++++ src/test/regress/sql/vacuum_stats.sql | 47 ++++++++++++ 2 files changed, 133 insertions(+) diff --git a/src/test/regress/expected/vacuum_stats.out b/src/test/regress/expected/vacuum_stats.out index df504318eeb..594dcdc1a96 100644 --- a/src/test/regress/expected/vacuum_stats.out +++ b/src/test/regress/expected/vacuum_stats.out @@ -29,3 +29,89 @@ AND relallvisible = (1 row) DROP TABLE vacstat_test; +-- Core GUC regression: reconnect with timing enabled at session startup. +-- Segment processes must keep the default off across coordinator startup +-- options, SET, and ROLLBACK. All three checks expect t. +\connect -reuse-previous=on "options='-c track_cost_delay_timing=on'" +SELECT bool_and(setting = 'off') AS segment_timing_local + FROM gp_dist_random('pg_settings') WHERE name = 'track_cost_delay_timing'; + segment_timing_local +---------------------- + t +(1 row) + +BEGIN; +SET track_cost_delay_timing = off; +SELECT bool_and(setting = 'off') AS segment_timing_local + FROM gp_dist_random('pg_settings') WHERE name = 'track_cost_delay_timing'; + segment_timing_local +---------------------- + t +(1 row) + +ROLLBACK; +SELECT bool_and(setting = 'off') AS segment_timing_local + FROM gp_dist_random('pg_settings') WHERE name = 'track_cost_delay_timing'; + segment_timing_local +---------------------- + t +(1 row) + +RESET track_cost_delay_timing; +-- Core index-summary regression: two indexes on the same table must give +-- exactly two summary rows. Joining by table OID alone used to multiply +-- rows and mix index timings; compare each index with its own segment sum. +CREATE TABLE core_summary_test (a int, b int) DISTRIBUTED BY (a); +CREATE INDEX core_summary_a ON core_summary_test(a); +CREATE INDEX core_summary_b ON core_summary_test(b); +INSERT INTO core_summary_test SELECT g, g FROM generate_series(1, 10000) g; +DELETE FROM core_summary_test WHERE a % 2 = 0; +CREATE TABLE core_timing_repl (a int) DISTRIBUTED REPLICATED; +INSERT INTO core_timing_repl SELECT generate_series(1, 1000); +DELETE FROM core_timing_repl; +VACUUM core_summary_test, core_timing_repl; +SELECT count(*) AS summary_indexes, + count(DISTINCT indexrelid) AS distinct_indexes + FROM gp_stat_all_indexes_summary WHERE relname = 'core_summary_test'; + summary_indexes | distinct_indexes +-----------------+------------------ + 2 | 2 +(1 row) + +SELECT bool_and(s.total_vacuum_time = d.total_vacuum_time) AS index_totals_match + FROM gp_stat_all_indexes_summary s + JOIN (SELECT indexrelid, sum(total_vacuum_time) AS total_vacuum_time + FROM gp_dist_random('pg_stat_all_indexes') + WHERE relname = 'core_summary_test' GROUP BY indexrelid) d + USING (indexrelid) + WHERE s.relname = 'core_summary_test'; + index_totals_match +-------------------- + t +(1 row) + +-- Native timing summaries work without a statistics extension. +SELECT count(*) = 2 AND bool_and(total_vacuum_time > 0) AS tables_vacuum_timed + FROM gp_stat_all_tables_summary + WHERE relname IN ('core_summary_test', 'core_timing_repl'); + tables_vacuum_timed +--------------------- + t +(1 row) + +-- Flush database timing before checking its cluster aggregate. +SELECT gp_stat_force_next_flush(); + gp_stat_force_next_flush +-------------------------- + +(1 row) + +SELECT total_vacuum_time > 0 AS database_vacuum_timed + FROM gp_stat_vacuum_summary + WHERE datname = current_database(); + database_vacuum_timed +----------------------- + t +(1 row) + +DROP TABLE core_summary_test, core_timing_repl; diff --git a/src/test/regress/sql/vacuum_stats.sql b/src/test/regress/sql/vacuum_stats.sql index 2a63e3b7388..9f5b35205c5 100644 --- a/src/test/regress/sql/vacuum_stats.sql +++ b/src/test/regress/sql/vacuum_stats.sql @@ -21,3 +21,50 @@ AND relallvisible = DROP TABLE vacstat_test; +-- Core GUC regression: reconnect with timing enabled at session startup. +-- Segment processes must keep the default off across coordinator startup +-- options, SET, and ROLLBACK. All three checks expect t. +\connect -reuse-previous=on "options='-c track_cost_delay_timing=on'" +SELECT bool_and(setting = 'off') AS segment_timing_local + FROM gp_dist_random('pg_settings') WHERE name = 'track_cost_delay_timing'; +BEGIN; +SET track_cost_delay_timing = off; +SELECT bool_and(setting = 'off') AS segment_timing_local + FROM gp_dist_random('pg_settings') WHERE name = 'track_cost_delay_timing'; +ROLLBACK; +SELECT bool_and(setting = 'off') AS segment_timing_local + FROM gp_dist_random('pg_settings') WHERE name = 'track_cost_delay_timing'; +RESET track_cost_delay_timing; + +-- Core index-summary regression: two indexes on the same table must give +-- exactly two summary rows. Joining by table OID alone used to multiply +-- rows and mix index timings; compare each index with its own segment sum. +CREATE TABLE core_summary_test (a int, b int) DISTRIBUTED BY (a); +CREATE INDEX core_summary_a ON core_summary_test(a); +CREATE INDEX core_summary_b ON core_summary_test(b); +INSERT INTO core_summary_test SELECT g, g FROM generate_series(1, 10000) g; +DELETE FROM core_summary_test WHERE a % 2 = 0; +CREATE TABLE core_timing_repl (a int) DISTRIBUTED REPLICATED; +INSERT INTO core_timing_repl SELECT generate_series(1, 1000); +DELETE FROM core_timing_repl; +VACUUM core_summary_test, core_timing_repl; +SELECT count(*) AS summary_indexes, + count(DISTINCT indexrelid) AS distinct_indexes + FROM gp_stat_all_indexes_summary WHERE relname = 'core_summary_test'; +SELECT bool_and(s.total_vacuum_time = d.total_vacuum_time) AS index_totals_match + FROM gp_stat_all_indexes_summary s + JOIN (SELECT indexrelid, sum(total_vacuum_time) AS total_vacuum_time + FROM gp_dist_random('pg_stat_all_indexes') + WHERE relname = 'core_summary_test' GROUP BY indexrelid) d + USING (indexrelid) + WHERE s.relname = 'core_summary_test'; +-- Native timing summaries work without a statistics extension. +SELECT count(*) = 2 AND bool_and(total_vacuum_time > 0) AS tables_vacuum_timed + FROM gp_stat_all_tables_summary + WHERE relname IN ('core_summary_test', 'core_timing_repl'); +-- Flush database timing before checking its cluster aggregate. +SELECT gp_stat_force_next_flush(); +SELECT total_vacuum_time > 0 AS database_vacuum_timed + FROM gp_stat_vacuum_summary + WHERE datname = current_database(); +DROP TABLE core_summary_test, core_timing_repl; From 6d12b7b8fb64b8c7b2f2e11d68aeb1efd45db052 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Sun, 1 Nov 2026 17:53:45 +0300 Subject: [PATCH 15/20] Fix GIN analyze delay attribution and AO timing test configuration --- src/backend/access/gin/ginfast.c | 12 ++++---- src/backend/access/gin/ginvacuum.c | 6 ++-- src/include/access/gin_private.h | 3 +- .../isolation2/expected/vacuum_ao_stats.out | 30 ++++++++++++++++++- src/test/isolation2/sql/vacuum_ao_stats.sql | 12 +++++++- 5 files changed, 51 insertions(+), 12 deletions(-) diff --git a/src/backend/access/gin/ginfast.c b/src/backend/access/gin/ginfast.c index 65b7f7ef3b7..d42f9dbd5f0 100644 --- a/src/backend/access/gin/ginfast.c +++ b/src/backend/access/gin/ginfast.c @@ -467,7 +467,7 @@ ginHeapTupleFastInsert(GinState *ginstate, GinTupleCollector *collector) * pending list not forcibly. */ if (needCleanup) - ginInsertCleanup(ginstate, false, true, false, NULL); + ginInsertCleanup(ginstate, false, true, false, false, NULL); } /* @@ -777,7 +777,7 @@ processPendingPage(BuildAccumulator *accum, KeyArray *ka, */ void ginInsertCleanup(GinState *ginstate, bool full_clean, - bool fill_fsm, bool forceCleanup, + bool fill_fsm, bool forceCleanup, bool is_analyze, IndexBulkDeleteResult *stats) { Relation index = ginstate->index; @@ -891,7 +891,7 @@ ginInsertCleanup(GinState *ginstate, bool full_clean, */ processPendingPage(&accum, &datums, page, FirstOffsetNumber); - vacuum_delay_point(false); + vacuum_delay_point(is_analyze); /* * Is it time to flush memory to disk? Flush if we are at the end of @@ -928,7 +928,7 @@ ginInsertCleanup(GinState *ginstate, bool full_clean, { ginEntryInsert(ginstate, attnum, key, category, list, nlist, NULL); - vacuum_delay_point(false); + vacuum_delay_point(is_analyze); } /* @@ -1001,7 +1001,7 @@ ginInsertCleanup(GinState *ginstate, bool full_clean, /* * Read next page in pending list */ - vacuum_delay_point(false); + vacuum_delay_point(is_analyze); buffer = ReadBuffer(index, blkno); LockBuffer(buffer, GIN_SHARE); page = BufferGetPage(buffer); @@ -1076,7 +1076,7 @@ gin_clean_pending_list(PG_FUNCTION_ARGS) GinState ginstate; initGinState(&ginstate, indexRel); - ginInsertCleanup(&ginstate, true, true, true, &stats); + ginInsertCleanup(&ginstate, true, true, true, false, &stats); } else ereport(DEBUG1, diff --git a/src/backend/access/gin/ginvacuum.c b/src/backend/access/gin/ginvacuum.c index 067224ab475..00230753b06 100644 --- a/src/backend/access/gin/ginvacuum.c +++ b/src/backend/access/gin/ginvacuum.c @@ -591,7 +591,7 @@ ginbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, * and cleanup any pending inserts */ ginInsertCleanup(&gvs.ginstate, !IsAutoVacuumWorkerProcess(), - false, true, stats); + false, true, false, stats); } /* we'll re-count the tuples each time */ @@ -704,7 +704,7 @@ ginvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats) if (IsAutoVacuumWorkerProcess()) { initGinState(&ginstate, index); - ginInsertCleanup(&ginstate, false, true, true, stats); + ginInsertCleanup(&ginstate, false, true, true, true, stats); } return stats; } @@ -718,7 +718,7 @@ ginvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats) stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult)); initGinState(&ginstate, index); ginInsertCleanup(&ginstate, !IsAutoVacuumWorkerProcess(), - false, true, stats); + false, true, false, stats); } memset(&idxStat, 0, sizeof(idxStat)); diff --git a/src/include/access/gin_private.h b/src/include/access/gin_private.h index 0aafe650c28..3f205aa269a 100644 --- a/src/include/access/gin_private.h +++ b/src/include/access/gin_private.h @@ -464,7 +464,8 @@ extern void ginHeapTupleFastCollect(GinState *ginstate, OffsetNumber attnum, Datum value, bool isNull, ItemPointer ht_ctid); extern void ginInsertCleanup(GinState *ginstate, bool full_clean, - bool fill_fsm, bool forceCleanup, IndexBulkDeleteResult *stats); + bool fill_fsm, bool forceCleanup, bool is_analyze, + IndexBulkDeleteResult *stats); /* ginpostinglist.c */ diff --git a/src/test/isolation2/expected/vacuum_ao_stats.out b/src/test/isolation2/expected/vacuum_ao_stats.out index 2bb73a4726b..ae5f6a5fbe2 100644 --- a/src/test/isolation2/expected/vacuum_ao_stats.out +++ b/src/test/isolation2/expected/vacuum_ao_stats.out @@ -9,6 +9,20 @@ -- The vacuum statistics of the core for append-optimized tables: the vacuum -- and delay times of the tables and their indexes, and vacuum_interrupt_count. -- +-- Timing and the cost limit are instance-local GUCs: configure the segments. +!\retcode gpconfig -c track_cost_delay_timing -v on --skipvalidation; +-- start_ignore +-- end_ignore +(exited with code 0) +!\retcode gpconfig -c vacuum_cost_limit -v 1 --skipvalidation; +-- start_ignore +-- end_ignore +(exited with code 0) +!\retcode gpstop -u; +-- start_ignore +-- end_ignore +(exited with code 0) + CREATE TABLE vacstat_ao_row (i int, v text) WITH (appendonly=true) DISTRIBUTED BY (i); CREATE CREATE TABLE vacstat_ao_col (i int, v text) WITH (appendonly=true, orientation=column) DISTRIBUTED BY (i); @@ -32,7 +46,7 @@ DELETE 1500 SET 1: SET vacuum_cost_delay = '1ms'; SET -1: SET vacuum_cost_limit = 10; +1: SET vacuum_cost_limit = 1; SET 1: VACUUM vacstat_ao_row, vacstat_ao_col; VACUUM @@ -145,3 +159,17 @@ VACUUM 1: DROP TABLE vacstat_ao_row, vacstat_ao_col; DROP 1q: ... + +-- Restore the test cluster defaults. +!\retcode gpconfig -r track_cost_delay_timing --skipvalidation; +-- start_ignore +-- end_ignore +(exited with code 0) +!\retcode gpconfig -r vacuum_cost_limit --skipvalidation; +-- start_ignore +-- end_ignore +(exited with code 0) +!\retcode gpstop -u; +-- start_ignore +-- end_ignore +(exited with code 0) diff --git a/src/test/isolation2/sql/vacuum_ao_stats.sql b/src/test/isolation2/sql/vacuum_ao_stats.sql index 99397a5819f..b51e5e7f99d 100644 --- a/src/test/isolation2/sql/vacuum_ao_stats.sql +++ b/src/test/isolation2/sql/vacuum_ao_stats.sql @@ -9,6 +9,11 @@ -- The vacuum statistics of the core for append-optimized tables: the vacuum -- and delay times of the tables and their indexes, and vacuum_interrupt_count. -- +-- Timing and the cost limit are instance-local GUCs: configure the segments. +!\retcode gpconfig -c track_cost_delay_timing -v on --skipvalidation; +!\retcode gpconfig -c vacuum_cost_limit -v 1 --skipvalidation; +!\retcode gpstop -u; + CREATE TABLE vacstat_ao_row (i int, v text) WITH (appendonly=true) DISTRIBUTED BY (i); CREATE TABLE vacstat_ao_col (i int, v text) WITH (appendonly=true, orientation=column) DISTRIBUTED BY (i); CREATE INDEX vacstat_ao_row_idx ON vacstat_ao_row (i); @@ -22,7 +27,7 @@ DELETE FROM vacstat_ao_col WHERE i % 2 = 0; -- tables and the indexes get vacuum and delay time on every segment. 1: SET track_cost_delay_timing = on; 1: SET vacuum_cost_delay = '1ms'; -1: SET vacuum_cost_limit = 10; +1: SET vacuum_cost_limit = 1; 1: VACUUM vacstat_ao_row, vacstat_ao_col; 1: SELECT relname, count(*) FILTER (WHERE total_vacuum_time > 0) AS segments_timed, count(*) FILTER (WHERE total_vacuum_delay_time > 0) AS segments_delayed @@ -91,3 +96,8 @@ DELETE FROM vacstat_ao_row WHERE i % 2 = 1; 1: DROP TABLE vacstat_ao_row, vacstat_ao_col; 1q: + +-- Restore the test cluster defaults. +!\retcode gpconfig -r track_cost_delay_timing --skipvalidation; +!\retcode gpconfig -r vacuum_cost_limit --skipvalidation; +!\retcode gpstop -u; From da51df874f1b303ba96925667fcad0e5a4cdb863 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Sun, 1 Nov 2026 17:54:36 +0300 Subject: [PATCH 16/20] Collect cumulative frozen-page vacuum statistics Reuse PostgreSQL 16 frozen_pages measurements for completed heap vacuums. Expose pages_frozen through native statistics and summary views, with documentation and reset/no-double-count coverage. --- doc/src/sgml/monitoring.sgml | 9 ++++ src/backend/access/heap/vacuumlazy.c | 2 +- src/backend/catalog/system_views.sql | 1 + .../catalog/system_views_gp_summary.sql | 3 ++ src/backend/commands/vacuum_ao.c | 2 +- src/backend/utils/activity/pgstat_relation.c | 8 +-- src/backend/utils/adt/pgstatfuncs.c | 1 + src/include/catalog/catversion.h | 2 +- src/include/catalog/pg_proc.dat | 5 ++ src/include/pgstat.h | 8 +-- src/test/modules/test_misc/Makefile | 2 +- src/test/modules/test_misc/meson.build | 1 + .../test_misc/t/021_vacuum_vm_pages.pl | 52 +++++++++++++++++++ src/test/regress/expected/rules.out | 3 ++ 14 files changed, 89 insertions(+), 10 deletions(-) create mode 100644 src/test/modules/test_misc/t/021_vacuum_vm_pages.pl diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml index ba1d71cd680..a852224f272 100644 --- a/doc/src/sgml/monitoring.sgml +++ b/doc/src/sgml/monitoring.sgml @@ -5230,6 +5230,15 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i + + + pages_frozen bigint + + Cumulative number of heap pages on which completed vacuums froze tuples. This counts freezing work, not the current number of all-frozen pages. Manual vacuum and autovacuum are both included; append-optimized + tables report zero. The counter is reset with the relation statistics. + + + visible_page_marks_cleared bigint diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c index c2eac3462f5..07d3ddad588 100644 --- a/src/backend/access/heap/vacuumlazy.c +++ b/src/backend/access/heap/vacuumlazy.c @@ -796,7 +796,7 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, vacrel->missed_dead_tuples, starttime, (PgStat_Counter) rint(VacuumDelayTime - startdelaytime), - VacuumFailsafeActive); + VacuumFailsafeActive, vacrel->frozen_pages); pgstat_progress_end_command(); if (instrument) diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql index f2b72af85f4..c3510c79924 100644 --- a/src/backend/catalog/system_views.sql +++ b/src/backend/catalog/system_views.sql @@ -709,6 +709,7 @@ CREATE VIEW pg_stat_all_tables AS pg_stat_get_total_vacuum_delay_time(C.oid) AS total_vacuum_delay_time, pg_stat_get_total_autovacuum_delay_time(C.oid) AS total_autovacuum_delay_time, pg_stat_get_vacuum_failsafe_count(C.oid) AS vacuum_failsafe_count, + pg_stat_get_pages_frozen(C.oid) AS pages_frozen, pg_stat_get_visible_page_marks_cleared(C.oid) AS visible_page_marks_cleared, pg_stat_get_frozen_page_marks_cleared(C.oid) AS frozen_page_marks_cleared FROM pg_class C LEFT JOIN diff --git a/src/backend/catalog/system_views_gp_summary.sql b/src/backend/catalog/system_views_gp_summary.sql index 8447253d413..9a9e8b1a1f2 100644 --- a/src/backend/catalog/system_views_gp_summary.sql +++ b/src/backend/catalog/system_views_gp_summary.sql @@ -147,6 +147,7 @@ SELECT m.total_vacuum_delay_time, m.total_autovacuum_delay_time, m.vacuum_failsafe_count, + m.pages_frozen, m.visible_page_marks_cleared, m.frozen_page_marks_cleared FROM @@ -184,6 +185,8 @@ FROM case when d.policytype = 'r' then (sum(total_vacuum_delay_time)/d.numsegments) else sum(total_vacuum_delay_time) end total_vacuum_delay_time, case when d.policytype = 'r' then (sum(total_autovacuum_delay_time)/d.numsegments) else sum(total_autovacuum_delay_time) end total_autovacuum_delay_time, sum(vacuum_failsafe_count)::bigint as vacuum_failsafe_count, + case when d.policytype = 'r' then (sum(pages_frozen)/d.numsegments)::bigint else sum(pages_frozen) end pages_frozen, + case when d.policytype = 'r' then (sum(visible_page_marks_cleared)/d.numsegments)::bigint else sum(visible_page_marks_cleared) end visible_page_marks_cleared, case when d.policytype = 'r' then (sum(frozen_page_marks_cleared)/d.numsegments)::bigint else sum(frozen_page_marks_cleared) end frozen_page_marks_cleared FROM diff --git a/src/backend/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c index bfd23a61e3a..f8fa0369873 100644 --- a/src/backend/commands/vacuum_ao.c +++ b/src/backend/commands/vacuum_ao.c @@ -554,7 +554,7 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy vacrelstats->live_tuples, vacrelstats->dead_tuples, (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(phase_end)), (PgStat_Counter) rint(VacuumDelayTime - phase_start_delay), - false, /* AO has no failsafe mode. */ + false, 0, /* AO has no failsafe mode or heap VM. */ ao_vacuum_phase == VACOPT_AO_POST_CLEANUP_PHASE); } diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c index b412feb71af..2b9675b7794 100644 --- a/src/backend/utils/activity/pgstat_relation.c +++ b/src/backend/utils/activity/pgstat_relation.c @@ -217,12 +217,12 @@ void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, TimestampTz starttime, PgStat_Counter delaytime, - bool failsafe) + bool failsafe, PgStat_Counter pages_frozen) { pgstat_report_vacuum_elapsed(tableoid, shared, livetuples, deadtuples, TimestampDifferenceMilliseconds(starttime, GetCurrentTimestamp()), - delaytime, failsafe, true); + delaytime, failsafe, pages_frozen, true); } /* @@ -235,7 +235,7 @@ void pgstat_report_vacuum_elapsed(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, PgStat_Counter elapsedtime, PgStat_Counter delaytime, - bool failsafe, bool is_complete) + bool failsafe, PgStat_Counter pages_frozen, bool is_complete) { PgStat_EntryRef *entry_ref; PgStatShared_Relation *shtabentry; @@ -296,6 +296,8 @@ pgstat_report_vacuum_elapsed(Oid tableoid, bool shared, tabentry->total_vacuum_delay_time += delaytime; } + tabentry->pages_frozen += pages_frozen; + if (failsafe) tabentry->vacuum_failsafe_count++; diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c index e94a5645ab4..4555acf1e61 100644 --- a/src/backend/utils/adt/pgstatfuncs.c +++ b/src/backend/utils/adt/pgstatfuncs.c @@ -122,6 +122,7 @@ PG_STAT_GET_RELENTRY_INT64(vacuum_count) /* pg_stat_get_vacuum_failsafe_count */ PG_STAT_GET_RELENTRY_INT64(vacuum_failsafe_count) +PG_STAT_GET_RELENTRY_INT64(pages_frozen) /* pg_stat_get_visible_page_marks_cleared */ PG_STAT_GET_RELENTRY_INT64(visible_page_marks_cleared) diff --git a/src/include/catalog/catversion.h b/src/include/catalog/catversion.h index 21dd3822811..a1995632ad9 100644 --- a/src/include/catalog/catversion.h +++ b/src/include/catalog/catversion.h @@ -60,6 +60,6 @@ */ /* 3yyymmddN */ -#define CATALOG_VERSION_NO 302610070 +#define CATALOG_VERSION_NO 302611010 #endif diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index d7ccc889973..4d3395f8b83 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -13083,3 +13083,8 @@ proargmodes => '{i,o,o,o,o,o,o,o,o,o,o,o,o,o}', proargnames => '{queueid,queueid,queries_submitted,queries_admitted,queries_rejected,queries_completed,elapsed_wait_secs,max_wait_secs,elapsed_exec_secs,max_exec_secs,total_cost,total_memory_kb,stat_reset_timestamp,have_stats}', prosrc => 'pg_stat_get_resqueue_stats' }, + +{ oid => '8694', descr => 'cumulative heap pages where vacuum froze tuples', + proname => 'pg_stat_get_pages_frozen', provolatile => 's', + proparallel => 'r', prorettype => 'int8', proargtypes => 'oid', + prosrc => 'pg_stat_get_pages_frozen' }, diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 528ded52928..90fd37ae609 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -241,7 +241,7 @@ typedef struct PgStat_TableXactStatus * ------------------------------------------------------------ */ -#define PGSTAT_FILE_FORMAT_ID 0x01A5BCB4 +#define PGSTAT_FILE_FORMAT_ID 0x01A5BCB5 typedef struct PgStat_ArchiverStats { @@ -471,6 +471,8 @@ typedef struct PgStat_StatTabEntry * failsafe mode (see vacuum_failsafe_age). */ PgStat_Counter vacuum_failsafe_count; + /* Cumulative work of completed heap vacuums, not current VM sizes. */ + PgStat_Counter pages_frozen; } PgStat_StatTabEntry; typedef struct PgStat_WalStats @@ -697,11 +699,11 @@ extern void pgstat_unlink_relation(Relation rel); extern void pgstat_report_vacuum_elapsed(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, PgStat_Counter elapsedtime, PgStat_Counter delaytime, - bool failsafe, bool is_complete); + bool failsafe, PgStat_Counter pages_frozen, bool is_complete); extern void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, TimestampTz starttime, PgStat_Counter delaytime, - bool failsafe); + bool failsafe, PgStat_Counter pages_frozen); extern void pgstat_report_index_vacuum_time(Relation rel, PgStat_Counter elapsedtime, PgStat_Counter delaytime, diff --git a/src/test/modules/test_misc/Makefile b/src/test/modules/test_misc/Makefile index b69beda44b7..2327f4d988f 100644 --- a/src/test/modules/test_misc/Makefile +++ b/src/test/modules/test_misc/Makefile @@ -17,5 +17,5 @@ endif # Native maintenance statistics coverage for the ic-tap CI job. .PHONY: installcheck-vacuum -installcheck-vacuum: PROVE_TESTS = t/016_index_vacuum_time.pl t/017_vacuum_failsafe.pl t/018_vacuum_interrupts.pl +installcheck-vacuum: PROVE_TESTS = t/016_index_vacuum_time.pl t/017_vacuum_failsafe.pl t/018_vacuum_interrupts.pl t/021_vacuum_vm_pages.pl installcheck-vacuum: installcheck diff --git a/src/test/modules/test_misc/meson.build b/src/test/modules/test_misc/meson.build index 88249df7be2..bf73ee408c1 100644 --- a/src/test/modules/test_misc/meson.build +++ b/src/test/modules/test_misc/meson.build @@ -21,6 +21,7 @@ tests += { 't/018_vacuum_interrupts.pl', 't/019_resqueue_stats_restart.pl', 't/020_custom_stats_restart.pl', + 't/021_vacuum_vm_pages.pl', 't/029_vacuum_resource_verbose.pl', ], }, diff --git a/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl b/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl new file mode 100644 index 00000000000..4dc6c0a3fbe --- /dev/null +++ b/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl @@ -0,0 +1,52 @@ +# Copyright (c) 2026, PostgreSQL Global Development Group + +# Completed-vacuum work is cumulative and does not require relallfrozen. +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +my $node = PostgreSQL::Test::Cluster->new('vacuum_vm_pages'); +$node->init; +$node->append_conf('postgresql.conf', 'autovacuum = off'); +$node->start; +$node->safe_psql('postgres', q{ +CREATE TABLE vm_pages (id int, padding text); +INSERT INTO vm_pages SELECT g, repeat('x', 100) FROM generate_series(1, 4000) g; +VACUUM (FREEZE) vm_pages; +}); +my $first = $node->safe_psql('postgres', q{ +SELECT pages_frozen FROM pg_stat_all_tables +WHERE relid = 'vm_pages'::regclass +}); +my $frozen = $first; +cmp_ok($frozen, '>', 0, 'VACUUM FREEZE records pages with freezing work'); +$node->safe_psql('postgres', 'VACUUM (FREEZE, DISABLE_PAGE_SKIPPING) vm_pages'); +is($node->safe_psql('postgres', q{ +SELECT pages_frozen FROM pg_stat_all_tables +WHERE relid = 'vm_pages'::regclass +}), $first, 'rescanning frozen visible pages does not recount them'); +$node->safe_psql('postgres', q{ +UPDATE vm_pages SET padding = 'changed'; +VACUUM (FREEZE) vm_pages; +}); +is($node->safe_psql('postgres', qq{ +SELECT pages_frozen > $frozen + AND visible_page_marks_cleared > 0 AND frozen_page_marks_cleared > 0 +FROM pg_stat_all_tables WHERE relid = 'vm_pages'::regclass +}), 't', 'new freezing work accumulates alongside cleared marks'); +$node->safe_psql('postgres', q{ +SELECT pg_stat_reset_single_table_counters('vm_pages'::regclass); +}); +is($node->safe_psql('postgres', q{ +SELECT pages_frozen = 0 +FROM pg_stat_all_tables WHERE relid = 'vm_pages'::regclass +}), 't', 'relation statistics reset clears the freezing work counter'); +is($node->safe_psql('postgres', q{ +SELECT NOT EXISTS (SELECT FROM pg_attribute + WHERE attrelid = 'pg_class'::regclass + AND attname = 'relallfrozen') +}), 't', 'no relallfrozen catalog field is required'); +$node->stop; +done_testing(); diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index 94c1f53b4c9..429eff9ce5a 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -1806,6 +1806,7 @@ pg_stat_all_tables| SELECT c.oid AS relid, pg_stat_get_total_vacuum_delay_time(c.oid) AS total_vacuum_delay_time, pg_stat_get_total_autovacuum_delay_time(c.oid) AS total_autovacuum_delay_time, pg_stat_get_vacuum_failsafe_count(c.oid) AS vacuum_failsafe_count, + pg_stat_get_pages_frozen(c.oid) AS pages_frozen, pg_stat_get_visible_page_marks_cleared(c.oid) AS visible_page_marks_cleared, pg_stat_get_frozen_page_marks_cleared(c.oid) AS frozen_page_marks_cleared FROM ((pg_class c @@ -2187,6 +2188,7 @@ pg_stat_sys_tables| SELECT relid, total_vacuum_delay_time, total_autovacuum_delay_time, vacuum_failsafe_count, + pages_frozen, visible_page_marks_cleared, frozen_page_marks_cleared FROM pg_stat_all_tables @@ -2244,6 +2246,7 @@ pg_stat_user_tables| SELECT relid, total_vacuum_delay_time, total_autovacuum_delay_time, vacuum_failsafe_count, + pages_frozen, visible_page_marks_cleared, frozen_page_marks_cleared FROM pg_stat_all_tables From 47f512379d41bf434cb12a24011255155f34bf98 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Sun, 1 Nov 2026 17:55:01 +0300 Subject: [PATCH 17/20] Collect cumulative all-visible-page vacuum statistics Count newly set all-visible VM marks while holding the heap page lock, including empty-page and second-pass cleanup paths. Expose pages_all_visible in native statistics, summary views and VERBOSE output, and extend regression coverage. --- doc/src/sgml/monitoring.sgml | 9 +++++++++ src/backend/access/heap/vacuumlazy.c | 17 ++++++++++++++++- src/backend/catalog/system_views.sql | 1 + src/backend/catalog/system_views_gp_summary.sql | 2 ++ src/backend/commands/vacuum_ao.c | 2 +- src/backend/utils/activity/pgstat_relation.c | 9 ++++++--- src/backend/utils/adt/pgstatfuncs.c | 1 + src/include/catalog/catversion.h | 2 +- src/include/catalog/pg_proc.dat | 4 ++++ src/include/pgstat.h | 9 ++++++--- .../modules/test_misc/t/021_vacuum_vm_pages.pl | 15 ++++++++------- src/test/regress/expected/rules.out | 3 +++ 12 files changed, 58 insertions(+), 16 deletions(-) diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml index a852224f272..5f0e61c7405 100644 --- a/doc/src/sgml/monitoring.sgml +++ b/doc/src/sgml/monitoring.sgml @@ -5239,6 +5239,15 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i + + + pages_all_visible bigint + + Cumulative number of heap pages newly marked all-visible by completed vacuums. Repeated scans of already-visible pages do not increment this counter. Manual vacuum and autovacuum are both included; append-optimized + tables report zero. The counter is reset with the relation statistics. + + + visible_page_marks_cleared bigint diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c index 07d3ddad588..9b2341f9202 100644 --- a/src/backend/access/heap/vacuumlazy.c +++ b/src/backend/access/heap/vacuumlazy.c @@ -206,6 +206,7 @@ typedef struct LVRelState BlockNumber scanned_pages; /* # pages examined (not skipped via VM) */ BlockNumber removed_pages; /* # pages removed by relation truncation */ BlockNumber frozen_pages; /* # pages with newly frozen tuples */ + BlockNumber all_visible_pages; /* # pages newly marked all-visible */ BlockNumber lpdead_item_pages; /* # pages with LP_DEAD items */ BlockNumber missed_dead_pages; /* # pages with missed dead tuples */ BlockNumber nonempty_pages; /* actually, last nonempty page + 1 */ @@ -596,6 +597,7 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, vacrel->scanned_pages = 0; vacrel->removed_pages = 0; vacrel->frozen_pages = 0; + vacrel->all_visible_pages = 0; vacrel->lpdead_item_pages = 0; vacrel->missed_dead_pages = 0; vacrel->nonempty_pages = 0; @@ -796,7 +798,8 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, vacrel->missed_dead_tuples, starttime, (PgStat_Counter) rint(VacuumDelayTime - startdelaytime), - VacuumFailsafeActive, vacrel->frozen_pages); + VacuumFailsafeActive, vacrel->frozen_pages, + vacrel->all_visible_pages); pgstat_progress_end_command(); if (instrument) @@ -895,6 +898,8 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, _("new relminmxid: %u, which is %d MXIDs ahead of previous value\n"), vacrel->NewRelminMxid, diff); } + appendStringInfo(&buf, _("pages marked all-visible: %u\n"), + vacrel->all_visible_pages); appendStringInfo(&buf, _("frozen: %u pages from table (%.2f%% of total) had %lld tuples frozen\n"), vacrel->frozen_pages, orig_rel_pages == 0 ? 100.0 : @@ -1313,6 +1318,9 @@ lazy_scan_heap(LVRelState *vacrel) */ PageSetAllVisible(page); MarkBufferDirty(buf); + /* Check the current VM bit while holding the heap page lock. */ + if (!VM_ALL_VISIBLE(vacrel->rel, blkno, &vmbuffer)) + vacrel->all_visible_pages++; visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr, vmbuffer, prunestate.visibility_cutoff_xid, flags); @@ -1386,6 +1394,8 @@ lazy_scan_heap(LVRelState *vacrel) * safe for REDO was logged when the page's tuples were frozen. */ Assert(!TransactionIdIsValid(prunestate.visibility_cutoff_xid)); + if (!VM_ALL_VISIBLE(vacrel->rel, blkno, &vmbuffer)) + vacrel->all_visible_pages++; visibilitymap_set(vacrel->rel, blkno, buf, InvalidXLogRecPtr, vmbuffer, InvalidTransactionId, VISIBILITYMAP_ALL_VISIBLE | @@ -1675,6 +1685,9 @@ lazy_scan_new_or_empty(LVRelState *vacrel, Buffer buf, BlockNumber blkno, */ if (!PageIsAllVisible(page)) { + if (!VM_ALL_VISIBLE(vacrel->rel, blkno, &vmbuffer)) + vacrel->all_visible_pages++; + START_CRIT_SECTION(); /* mark buffer dirty before writing a WAL record */ @@ -2811,6 +2824,8 @@ lazy_vacuum_heap_page(LVRelState *vacrel, BlockNumber blkno, Buffer buffer, } PageSetAllVisible(page); + if (!VM_ALL_VISIBLE(vacrel->rel, blkno, &vmbuffer)) + vacrel->all_visible_pages++; visibilitymap_set(vacrel->rel, blkno, buffer, InvalidXLogRecPtr, vmbuffer, visibility_cutoff_xid, flags); } diff --git a/src/backend/catalog/system_views.sql b/src/backend/catalog/system_views.sql index c3510c79924..e49d1baad4f 100644 --- a/src/backend/catalog/system_views.sql +++ b/src/backend/catalog/system_views.sql @@ -710,6 +710,7 @@ CREATE VIEW pg_stat_all_tables AS pg_stat_get_total_autovacuum_delay_time(C.oid) AS total_autovacuum_delay_time, pg_stat_get_vacuum_failsafe_count(C.oid) AS vacuum_failsafe_count, pg_stat_get_pages_frozen(C.oid) AS pages_frozen, + pg_stat_get_pages_all_visible(C.oid) AS pages_all_visible, pg_stat_get_visible_page_marks_cleared(C.oid) AS visible_page_marks_cleared, pg_stat_get_frozen_page_marks_cleared(C.oid) AS frozen_page_marks_cleared FROM pg_class C LEFT JOIN diff --git a/src/backend/catalog/system_views_gp_summary.sql b/src/backend/catalog/system_views_gp_summary.sql index 9a9e8b1a1f2..c3bdb99b87c 100644 --- a/src/backend/catalog/system_views_gp_summary.sql +++ b/src/backend/catalog/system_views_gp_summary.sql @@ -148,6 +148,7 @@ SELECT m.total_autovacuum_delay_time, m.vacuum_failsafe_count, m.pages_frozen, + m.pages_all_visible, m.visible_page_marks_cleared, m.frozen_page_marks_cleared FROM @@ -186,6 +187,7 @@ FROM case when d.policytype = 'r' then (sum(total_autovacuum_delay_time)/d.numsegments) else sum(total_autovacuum_delay_time) end total_autovacuum_delay_time, sum(vacuum_failsafe_count)::bigint as vacuum_failsafe_count, case when d.policytype = 'r' then (sum(pages_frozen)/d.numsegments)::bigint else sum(pages_frozen) end pages_frozen, + case when d.policytype = 'r' then (sum(pages_all_visible)/d.numsegments)::bigint else sum(pages_all_visible) end pages_all_visible, case when d.policytype = 'r' then (sum(visible_page_marks_cleared)/d.numsegments)::bigint else sum(visible_page_marks_cleared) end visible_page_marks_cleared, case when d.policytype = 'r' then (sum(frozen_page_marks_cleared)/d.numsegments)::bigint else sum(frozen_page_marks_cleared) end frozen_page_marks_cleared diff --git a/src/backend/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c index f8fa0369873..f59b870e82d 100644 --- a/src/backend/commands/vacuum_ao.c +++ b/src/backend/commands/vacuum_ao.c @@ -554,7 +554,7 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy vacrelstats->live_tuples, vacrelstats->dead_tuples, (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(phase_end)), (PgStat_Counter) rint(VacuumDelayTime - phase_start_delay), - false, 0, /* AO has no failsafe mode or heap VM. */ + false, 0, 0, /* AO has no failsafe mode or heap VM. */ ao_vacuum_phase == VACOPT_AO_POST_CLEANUP_PHASE); } diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c index 2b9675b7794..fd42ae3cceb 100644 --- a/src/backend/utils/activity/pgstat_relation.c +++ b/src/backend/utils/activity/pgstat_relation.c @@ -217,12 +217,13 @@ void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, TimestampTz starttime, PgStat_Counter delaytime, - bool failsafe, PgStat_Counter pages_frozen) + bool failsafe, PgStat_Counter pages_frozen, + PgStat_Counter pages_all_visible) { pgstat_report_vacuum_elapsed(tableoid, shared, livetuples, deadtuples, TimestampDifferenceMilliseconds(starttime, GetCurrentTimestamp()), - delaytime, failsafe, pages_frozen, true); + delaytime, failsafe, pages_frozen, pages_all_visible, true); } /* @@ -235,7 +236,8 @@ void pgstat_report_vacuum_elapsed(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, PgStat_Counter elapsedtime, PgStat_Counter delaytime, - bool failsafe, PgStat_Counter pages_frozen, bool is_complete) + bool failsafe, PgStat_Counter pages_frozen, + PgStat_Counter pages_all_visible, bool is_complete) { PgStat_EntryRef *entry_ref; PgStatShared_Relation *shtabentry; @@ -297,6 +299,7 @@ pgstat_report_vacuum_elapsed(Oid tableoid, bool shared, } tabentry->pages_frozen += pages_frozen; + tabentry->pages_all_visible += pages_all_visible; if (failsafe) tabentry->vacuum_failsafe_count++; diff --git a/src/backend/utils/adt/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c index 4555acf1e61..a9e3f66a8a9 100644 --- a/src/backend/utils/adt/pgstatfuncs.c +++ b/src/backend/utils/adt/pgstatfuncs.c @@ -123,6 +123,7 @@ PG_STAT_GET_RELENTRY_INT64(vacuum_count) /* pg_stat_get_vacuum_failsafe_count */ PG_STAT_GET_RELENTRY_INT64(vacuum_failsafe_count) PG_STAT_GET_RELENTRY_INT64(pages_frozen) +PG_STAT_GET_RELENTRY_INT64(pages_all_visible) /* pg_stat_get_visible_page_marks_cleared */ PG_STAT_GET_RELENTRY_INT64(visible_page_marks_cleared) diff --git a/src/include/catalog/catversion.h b/src/include/catalog/catversion.h index a1995632ad9..287ec7c0f01 100644 --- a/src/include/catalog/catversion.h +++ b/src/include/catalog/catversion.h @@ -60,6 +60,6 @@ */ /* 3yyymmddN */ -#define CATALOG_VERSION_NO 302611010 +#define CATALOG_VERSION_NO 302611241 #endif diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat index 4d3395f8b83..1654b79c719 100644 --- a/src/include/catalog/pg_proc.dat +++ b/src/include/catalog/pg_proc.dat @@ -13088,3 +13088,7 @@ proname => 'pg_stat_get_pages_frozen', provolatile => 's', proparallel => 'r', prorettype => 'int8', proargtypes => 'oid', prosrc => 'pg_stat_get_pages_frozen' }, +{ oid => '8695', descr => 'cumulative heap pages newly marked all-visible by vacuum', + proname => 'pg_stat_get_pages_all_visible', provolatile => 's', + proparallel => 'r', prorettype => 'int8', proargtypes => 'oid', + prosrc => 'pg_stat_get_pages_all_visible' }, diff --git a/src/include/pgstat.h b/src/include/pgstat.h index 90fd37ae609..a315fbd7238 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -241,7 +241,7 @@ typedef struct PgStat_TableXactStatus * ------------------------------------------------------------ */ -#define PGSTAT_FILE_FORMAT_ID 0x01A5BCB5 +#define PGSTAT_FILE_FORMAT_ID 0x01A5BCC1 typedef struct PgStat_ArchiverStats { @@ -473,6 +473,7 @@ typedef struct PgStat_StatTabEntry PgStat_Counter vacuum_failsafe_count; /* Cumulative work of completed heap vacuums, not current VM sizes. */ PgStat_Counter pages_frozen; + PgStat_Counter pages_all_visible; } PgStat_StatTabEntry; typedef struct PgStat_WalStats @@ -699,11 +700,13 @@ extern void pgstat_unlink_relation(Relation rel); extern void pgstat_report_vacuum_elapsed(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, PgStat_Counter elapsedtime, PgStat_Counter delaytime, - bool failsafe, PgStat_Counter pages_frozen, bool is_complete); + bool failsafe, PgStat_Counter pages_frozen, + PgStat_Counter pages_all_visible, bool is_complete); extern void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, TimestampTz starttime, PgStat_Counter delaytime, - bool failsafe, PgStat_Counter pages_frozen); + bool failsafe, PgStat_Counter pages_frozen, + PgStat_Counter pages_all_visible); extern void pgstat_report_index_vacuum_time(Relation rel, PgStat_Counter elapsedtime, PgStat_Counter delaytime, diff --git a/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl b/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl index 4dc6c0a3fbe..0163530af3f 100644 --- a/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl +++ b/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl @@ -17,14 +17,15 @@ VACUUM (FREEZE) vm_pages; }); my $first = $node->safe_psql('postgres', q{ -SELECT pages_frozen FROM pg_stat_all_tables +SELECT pages_frozen, pages_all_visible FROM pg_stat_all_tables WHERE relid = 'vm_pages'::regclass }); -my $frozen = $first; +my ($frozen, $visible) = split /\|/, $first; cmp_ok($frozen, '>', 0, 'VACUUM FREEZE records pages with freezing work'); +cmp_ok($visible, '>', 0, 'VACUUM records new all-visible marks'); $node->safe_psql('postgres', 'VACUUM (FREEZE, DISABLE_PAGE_SKIPPING) vm_pages'); is($node->safe_psql('postgres', q{ -SELECT pages_frozen FROM pg_stat_all_tables +SELECT pages_frozen, pages_all_visible FROM pg_stat_all_tables WHERE relid = 'vm_pages'::regclass }), $first, 'rescanning frozen visible pages does not recount them'); $node->safe_psql('postgres', q{ @@ -32,17 +33,17 @@ VACUUM (FREEZE) vm_pages; }); is($node->safe_psql('postgres', qq{ -SELECT pages_frozen > $frozen +SELECT pages_frozen > $frozen AND pages_all_visible > $visible AND visible_page_marks_cleared > 0 AND frozen_page_marks_cleared > 0 FROM pg_stat_all_tables WHERE relid = 'vm_pages'::regclass -}), 't', 'new freezing work accumulates alongside cleared marks'); +}), 't', 'new freezing and visibility work accumulates alongside cleared marks'); $node->safe_psql('postgres', q{ SELECT pg_stat_reset_single_table_counters('vm_pages'::regclass); }); is($node->safe_psql('postgres', q{ -SELECT pages_frozen = 0 +SELECT pages_frozen = 0 AND pages_all_visible = 0 FROM pg_stat_all_tables WHERE relid = 'vm_pages'::regclass -}), 't', 'relation statistics reset clears the freezing work counter'); +}), 't', 'relation statistics reset clears both work counters'); is($node->safe_psql('postgres', q{ SELECT NOT EXISTS (SELECT FROM pg_attribute WHERE attrelid = 'pg_class'::regclass diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out index 429eff9ce5a..625eec93cc6 100644 --- a/src/test/regress/expected/rules.out +++ b/src/test/regress/expected/rules.out @@ -1807,6 +1807,7 @@ pg_stat_all_tables| SELECT c.oid AS relid, pg_stat_get_total_autovacuum_delay_time(c.oid) AS total_autovacuum_delay_time, pg_stat_get_vacuum_failsafe_count(c.oid) AS vacuum_failsafe_count, pg_stat_get_pages_frozen(c.oid) AS pages_frozen, + pg_stat_get_pages_all_visible(c.oid) AS pages_all_visible, pg_stat_get_visible_page_marks_cleared(c.oid) AS visible_page_marks_cleared, pg_stat_get_frozen_page_marks_cleared(c.oid) AS frozen_page_marks_cleared FROM ((pg_class c @@ -2189,6 +2190,7 @@ pg_stat_sys_tables| SELECT relid, total_autovacuum_delay_time, vacuum_failsafe_count, pages_frozen, + pages_all_visible, visible_page_marks_cleared, frozen_page_marks_cleared FROM pg_stat_all_tables @@ -2247,6 +2249,7 @@ pg_stat_user_tables| SELECT relid, total_autovacuum_delay_time, vacuum_failsafe_count, pages_frozen, + pages_all_visible, visible_page_marks_cleared, frozen_page_marks_cleared FROM pg_stat_all_tables From 82f160fa0a95fd87d5a97483faf57499586a1cf4 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Sun, 1 Nov 2026 18:06:33 +0300 Subject: [PATCH 18/20] Count only errors escaping table vacuum as interruptions Count at the table access method error boundary instead of error-context callbacks, so caught expression-index exceptions during AO compaction do not inflate vacuum_interrupt_count. Preserve heap diagnostic context and rethrow escaping errors. Wait for VacuumDelay before cancellation and cover caught and escaping index exceptions for both AO storage orientations. --- doc/src/sgml/monitoring.sgml | 7 +- src/backend/access/heap/vacuumlazy.c | 4 -- src/backend/commands/vacuum.c | 20 +++++- src/backend/commands/vacuum_ao.c | 28 -------- src/backend/utils/activity/pgstat_database.c | 8 +-- .../test_misc/t/018_vacuum_interrupts.pl | 71 ++++++++++++++++++- 6 files changed, 97 insertions(+), 41 deletions(-) diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml index 5f0e61c7405..47b28fa18df 100644 --- a/doc/src/sgml/monitoring.sgml +++ b/doc/src/sgml/monitoring.sgml @@ -4829,8 +4829,11 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i vacuum_interrupt_count bigint - Number of times a vacuum in this database was interrupted by an error, - the vacuum of an append-optimized table included. In a Cloudberry + Number of errors escaping the table access method during vacuum, + including heap lazy vacuum and append-optimized vacuum phases. Errors + caught inside an index function, errors before entering the access + method (such as opening the relation), and heap VACUUM FULL + are not counted. In a Cloudberry cluster the count is kept by the instance on which the vacuum failed: a vacuum dispatched to the segments that fails there is counted by those segments, not by the coordinator. A segment reports the count diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c index 9b2341f9202..c3684377385 100644 --- a/src/backend/access/heap/vacuumlazy.c +++ b/src/backend/access/heap/vacuumlazy.c @@ -3692,10 +3692,6 @@ vacuum_error_callback(void *arg) { LVRelState *errinfo = arg; - /* Ignore non-error reports that also invoke this callback. */ - if (errinfo->rel != NULL && geterrlevel() == ERROR) - pgstat_count_vacuum_error(errinfo->rel->rd_rel->relisshared); - switch (errinfo->phase) { case VACUUM_ERRCB_PHASE_SCAN_HEAP: diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c index 0bc6cf39905..e29aed054d3 100644 --- a/src/backend/commands/vacuum.c +++ b/src/backend/commands/vacuum.c @@ -2890,7 +2890,25 @@ vacuum_rel(Oid relid, RangeVar *relation, VacuumParams *params, cluster_rel(relid, InvalidOid, &cluster_params); } else /* Heap vacuum or AO/CO vacuum in specific phase */ - table_relation_vacuum(rel, params, bstrategy); + { + bool shared = rel->rd_rel->relisshared; + + /* + * Count errors only when they escape the access method. Index + * expressions can raise and catch errors internally (for example + * during AO compaction) without interrupting this vacuum. + */ + PG_TRY(); + { + table_relation_vacuum(rel, params, bstrategy); + } + PG_CATCH(); + { + pgstat_count_vacuum_error(shared); + PG_RE_THROW(); + } + PG_END_TRY(); + } } if (IS_QD_OR_SINGLENODE() && (params->options & VACOPT_FULL)) diff --git a/src/backend/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c index f59b870e82d..9758759f82c 100644 --- a/src/backend/commands/vacuum_ao.c +++ b/src/backend/commands/vacuum_ao.c @@ -173,7 +173,6 @@ static void ao_measure_index_resources(Relation indrel, AOVacuumRelStats *vacrelstats, bool verbose); static void ao_report_index_vacuum_time(Relation indrel, TimestampTz starttime, double startdelaytime); -static void ao_vacuum_error_callback(void *arg); static void ao_vacuum_rel_pre_cleanup(Relation onerel, VacuumParams *params, BufferAccessStrategy bstrategy, AOVacuumRelStats *vacrelstats) @@ -442,7 +441,6 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy LVExtStatCounters *extcounters; bool verbose = (params->options & VACOPT_VERBOSE) != 0; PgStat_CommonCounts index_start = {0}; - ErrorContextCallback errcallback; instr_time phase_start; instr_time phase_end; double phase_start_delay; @@ -491,12 +489,6 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy if (vacrelstats->extstats != NULL) index_start = vacrelstats->extstats->indexes; - /* Count the vacuums of the relation that an error interrupts */ - errcallback.callback = ao_vacuum_error_callback; - errcallback.arg = rel; - errcallback.previous = error_context_stack; - error_context_stack = &errcallback; - INSTR_TIME_SET_CURRENT(phase_start); phase_start_delay = VacuumDelayTime; @@ -564,8 +556,6 @@ ao_vacuum_rel(Relation rel, VacuumParams *params, BufferAccessStrategy bstrategy cleanup_vacrelstats(&vacrelstats); } - error_context_stack = errcallback.previous; - if (extcounters != NULL) pfree(extcounters); } @@ -679,24 +669,6 @@ ao_measure_index_resources(Relation indrel, LVExtStatCounters *counters, pfree(counters); } -/* - * Error context callback of an append-optimized vacuum phase. - * - * Like vacuum_error_callback() of the heap, count a vacuum interrupted by an - * actual ERROR, not by a lower-severity report that merely carries this - * context, in vacuum_interrupt_count of the database. We are inside the - * error handler, so pgstat_count_vacuum_error() only bumps a counter. The - * callback adds no context line: the phases report their own progress. - */ -static void -ao_vacuum_error_callback(void *arg) -{ - Relation rel = (Relation) arg; - - if (geterrlevel() == ERROR) - pgstat_count_vacuum_error(rel->rd_rel->relisshared); -} - /* * Accumulate one vacuum pass over an index of an append-optimized table * into the index's cumulative vacuum and delay times, as the heap does in diff --git a/src/backend/utils/activity/pgstat_database.c b/src/backend/utils/activity/pgstat_database.c index a320a735c22..129531516e2 100644 --- a/src/backend/utils/activity/pgstat_database.c +++ b/src/backend/utils/activity/pgstat_database.c @@ -37,7 +37,7 @@ static int pgStatXactRollback = 0; static PgStat_Counter pgLastSessionReportTime = 0; /* - * Vacuums interrupted by an error, counted from the vacuum error callback + * Vacuums interrupted by an error, counted when errors escape the table vacuum * and folded into the pending database entries at transaction end. */ static PgStat_Counter pgStatVacuumErrors = 0; @@ -359,9 +359,9 @@ pgstat_should_report_connstat(void) /* * Count a vacuum that was interrupted by an error. * - * This is called from the vacuum error callback, that is from inside the - * error handler, so it must not do anything that could fail or block: the - * error may well have been raised by the locking code itself, possibly + * This is called from the table vacuum PG_CATCH handler, so it must not + * do anything that could fail or block: the error may well have been + * raised by the locking code itself, possibly * while holding an LWLock. Just bump a counter here; the counter reaches * the pending database entry in AtEOXact_PgStat_Database(), once the * transaction end has released the locks we might have been holding. diff --git a/src/test/modules/test_misc/t/018_vacuum_interrupts.pl b/src/test/modules/test_misc/t/018_vacuum_interrupts.pl index f1cb11462ac..ccb669b3074 100644 --- a/src/test/modules/test_misc/t/018_vacuum_interrupts.pl +++ b/src/test/modules/test_misc/t/018_vacuum_interrupts.pl @@ -43,11 +43,13 @@ VACUUM vacstat_int; ]); -# Wait until the vacuum is actually running, then cancel it. +# Wait for a cost-delay point inside the vacuum, not merely an active query. +# The query becomes active before the table vacuum error handler is installed. $node->poll_query_until( 'postgres', qq[ SELECT count(*) = 1 FROM pg_stat_activity - WHERE application_name = '$appname' AND query LIKE 'VACUUM%' AND state = 'active']) + WHERE application_name = '$appname' AND query LIKE 'VACUUM%' AND state = 'active' + AND wait_event = 'VacuumDelay']) or die "timed out waiting for the vacuum to start"; my $cancelled = $node->safe_psql( @@ -66,6 +68,71 @@ 't', 'vacuum_interrupt_count advanced in pg_stat_vacuum'); +# AO compaction evaluates expression indexes. Exceptions caught inside an +# index function must not count as interrupted vacuums, while escaping ones +# must count exactly once. +$node->safe_psql('postgres', q{ +CREATE FUNCTION vacstat_index_value(i int) RETURNS int +LANGUAGE plpgsql IMMUTABLE AS $$ +BEGIN + IF current_setting('application_name') = 'vacuum_unhandled_error' THEN + RAISE EXCEPTION 'unhandled index error'; + END IF; + BEGIN + RAISE EXCEPTION 'handled index error'; + EXCEPTION WHEN raise_exception THEN + IF current_setting('application_name') = 'vacuum_handled_error' THEN + RAISE NOTICE 'caught index error during compaction'; + END IF; + RETURN i; + END; +END; +$$; +}); + +for my $orientation ('row', 'column') +{ + my $table = "vacstat_caught_$orientation"; + $node->safe_psql('postgres', qq{ +CREATE TABLE $table (id int) WITH (appendonly=true, orientation=$orientation); +CREATE INDEX ${table}_idx ON $table (vacstat_index_value(id)); +INSERT INTO $table SELECT generate_series(1, 100); +DELETE FROM $table WHERE id % 2 = 0; +}); + my $before = $node->safe_psql('postgres', q{ +SELECT vacuum_interrupt_count FROM pg_stat_vacuum WHERE datname = current_database() +}); + my ($stdout, $stderr); + is($node->psql('postgres', qq{ +SET application_name = 'vacuum_handled_error'; +SET gp_appendonly_compaction_threshold = 1; +VACUUM $table; +}, stdout => \$stdout, stderr => \$stderr), 0, + "$orientation vacuum succeeds with caught index exceptions"); + like($stderr, qr/caught index error during compaction/, + "$orientation compaction evaluated the exception-handling index function"); + is($node->safe_psql('postgres', q{ +SELECT vacuum_interrupt_count FROM pg_stat_vacuum WHERE datname = current_database() +}), $before, "$orientation caught exceptions do not increment interruptions"); + is($node->safe_psql('postgres', "SELECT count(*) FROM $table"), '50', + "$orientation vacuum preserves surviving rows"); + + $node->safe_psql('postgres', "DELETE FROM $table WHERE id <= 25"); + isnt($node->psql('postgres', qq{ +SET application_name = 'vacuum_unhandled_error'; +SET gp_appendonly_compaction_threshold = 1; +VACUUM $table; +}, stdout => \$stdout, stderr => \$stderr), 0, + "$orientation vacuum fails on an escaping index exception"); + like($stderr, qr/unhandled index error/, + "$orientation reports the escaping index exception"); + is($node->safe_psql('postgres', q{ +SELECT vacuum_interrupt_count FROM pg_stat_vacuum WHERE datname = current_database() +}), $before + 1, "$orientation escaping exception counts exactly once"); + $node->safe_psql('postgres', "DROP TABLE $table"); +} +$node->safe_psql('postgres', 'DROP FUNCTION vacstat_index_value(int)'); + $node->stop; done_testing(); From 23ed5dc0d6b12173640c537934e21328eed8acae Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Tue, 17 Nov 2026 00:05:10 +0300 Subject: [PATCH 19/20] Use ASF license headers for native maintenance statistics tests --- .../isolation/specs/vacuum-extending-freeze.spec | 16 ++++++++++++++++ src/test/isolation2/expected/vacuum_ao_stats.out | 16 ++++++++++++++++ src/test/isolation2/sql/vacuum_ao_stats.sql | 16 ++++++++++++++++ .../modules/test_misc/t/016_index_vacuum_time.pl | 16 +++++++++++++++- .../modules/test_misc/t/017_vacuum_failsafe.pl | 16 +++++++++++++++- .../modules/test_misc/t/018_vacuum_interrupts.pl | 16 +++++++++++++++- .../modules/test_misc/t/021_vacuum_vm_pages.pl | 16 +++++++++++++++- 7 files changed, 108 insertions(+), 4 deletions(-) diff --git a/src/test/isolation/specs/vacuum-extending-freeze.spec b/src/test/isolation/specs/vacuum-extending-freeze.spec index 2ba87eb3d23..a902779d9ab 100644 --- a/src/test/isolation/specs/vacuum-extending-freeze.spec +++ b/src/test/isolation/specs/vacuum-extending-freeze.spec @@ -1,3 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to You under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of the +# License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. + # Check cumulative counts of cleared VM bits after freezing. # A repeatable-read transaction keeps deleted tuples visible to its snapshot. # It also caches the table statistics before the other session deletes rows: diff --git a/src/test/isolation2/expected/vacuum_ao_stats.out b/src/test/isolation2/expected/vacuum_ao_stats.out index ae5f6a5fbe2..08f5be81186 100644 --- a/src/test/isolation2/expected/vacuum_ao_stats.out +++ b/src/test/isolation2/expected/vacuum_ao_stats.out @@ -1,3 +1,19 @@ +-- Licensed to the Apache Software Foundation (ASF) under one or more +-- contributor license agreements. See the NOTICE file distributed +-- with this work for additional information regarding copyright +-- ownership. The ASF licenses this file to You under the Apache +-- License, Version 2.0 (the "License"); you may not use this file +-- except in compliance with the License. You may obtain a copy of the +-- License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +-- implied. See the License for the specific language governing +-- permissions and limitations under the License. + -- start_matchsubs -- -- # the segment that reports the injected error first is not deterministic diff --git a/src/test/isolation2/sql/vacuum_ao_stats.sql b/src/test/isolation2/sql/vacuum_ao_stats.sql index b51e5e7f99d..b6413a383df 100644 --- a/src/test/isolation2/sql/vacuum_ao_stats.sql +++ b/src/test/isolation2/sql/vacuum_ao_stats.sql @@ -1,3 +1,19 @@ +-- Licensed to the Apache Software Foundation (ASF) under one or more +-- contributor license agreements. See the NOTICE file distributed +-- with this work for additional information regarding copyright +-- ownership. The ASF licenses this file to You under the Apache +-- License, Version 2.0 (the "License"); you may not use this file +-- except in compliance with the License. You may obtain a copy of the +-- License at +-- +-- http://www.apache.org/licenses/LICENSE-2.0 +-- +-- Unless required by applicable law or agreed to in writing, software +-- distributed under the License is distributed on an "AS IS" BASIS, +-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +-- implied. See the License for the specific language governing +-- permissions and limitations under the License. + -- start_matchsubs -- -- # the segment that reports the injected error first is not deterministic diff --git a/src/test/modules/test_misc/t/016_index_vacuum_time.pl b/src/test/modules/test_misc/t/016_index_vacuum_time.pl index 4eb02ab2517..61848e9bfab 100644 --- a/src/test/modules/test_misc/t/016_index_vacuum_time.pl +++ b/src/test/modules/test_misc/t/016_index_vacuum_time.pl @@ -1,4 +1,18 @@ -# Copyright (c) 2026, PostgreSQL Global Development Group +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to You under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of the +# License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. # Test the total_vacuum_time counter of pg_stat_all_indexes: the time vacuum # spent processing each index, accumulated over bulkdelete and cleanup passes, diff --git a/src/test/modules/test_misc/t/017_vacuum_failsafe.pl b/src/test/modules/test_misc/t/017_vacuum_failsafe.pl index 9332c250477..f6393cdfcac 100644 --- a/src/test/modules/test_misc/t/017_vacuum_failsafe.pl +++ b/src/test/modules/test_misc/t/017_vacuum_failsafe.pl @@ -1,4 +1,18 @@ -# Copyright (c) 2026, PostgreSQL Global Development Group +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to You under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of the +# License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. # Test that vacuums entering the wraparound failsafe mode are counted in # pg_stat_all_tables.vacuum_failsafe_count and aggregated per database in diff --git a/src/test/modules/test_misc/t/018_vacuum_interrupts.pl b/src/test/modules/test_misc/t/018_vacuum_interrupts.pl index ccb669b3074..a3b532bfc78 100644 --- a/src/test/modules/test_misc/t/018_vacuum_interrupts.pl +++ b/src/test/modules/test_misc/t/018_vacuum_interrupts.pl @@ -1,4 +1,18 @@ -# Copyright (c) 2026, PostgreSQL Global Development Group +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to You under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of the +# License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. # Test the vacuum_interrupt_count counter of pg_stat_vacuum. # diff --git a/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl b/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl index 0163530af3f..7e05fb36d36 100644 --- a/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl +++ b/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl @@ -1,4 +1,18 @@ -# Copyright (c) 2026, PostgreSQL Global Development Group +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed +# with this work for additional information regarding copyright +# ownership. The ASF licenses this file to You under the Apache +# License, Version 2.0 (the "License"); you may not use this file +# except in compliance with the License. You may obtain a copy of the +# License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or +# implied. See the License for the specific language governing +# permissions and limitations under the License. # Completed-vacuum work is cumulative and does not require relallfrozen. use strict; From 7cfaa1bf7325cc126b197bdf224a423acf5d8194 Mon Sep 17 00:00:00 2001 From: Alena Rybakina Date: Thu, 3 Dec 2026 18:04:34 +0300 Subject: [PATCH 20/20] Address native maintenance statistics review Count visibility-map clears by heap_force_kill and cover repeated surgery on the same frozen page. Preserve the upstream ginInsertCleanup signature with a separate auto-analyze entry point so cleanup delays retain their ANALYZE attribution without changing existing GIN callers. Use instr_time and nearest-millisecond rounding for maintenance timing, including serial and parallel index passes. Remove the INT_MAX duration cap and avoid rounding every short index pass up to one millisecond. Clarify per-instance interrupt and failsafe counts in cluster summaries. Replace fixed AO statistics waits with a forced cluster flush, remove the obsolete wall-clock bound and relallfrozen absence assertion, and restore auto-analyze settings immediately after the test wait. --- contrib/pg_surgery/expected/heap_surgery.out | 30 +++++++++++++++++ contrib/pg_surgery/heap_surgery.c | 4 +-- contrib/pg_surgery/sql/heap_surgery.sql | 11 +++++++ doc/src/sgml/monitoring.sgml | 12 +++++-- src/backend/access/gin/ginfast.c | 29 +++++++++++++++-- src/backend/access/gin/ginvacuum.c | 6 ++-- src/backend/access/heap/vacuumlazy.c | 26 ++++++++++----- .../catalog/system_views_gp_summary.sql | 1 + src/backend/commands/analyze.c | 8 +++-- src/backend/commands/vacuum_ao.c | 17 ++++++---- src/backend/commands/vacuumparallel.c | 13 ++++++-- src/backend/utils/activity/pgstat_relation.c | 18 ++++++++--- src/include/access/gin_private.h | 4 ++- src/include/pgstat.h | 4 +-- .../expected/vacuum_analyze_stats.out | 21 ++++++------ .../isolation2/expected/vacuum_ao_stats.out | 32 ++++--------------- .../isolation2/sql/vacuum_analyze_stats.sql | 9 ++++-- src/test/isolation2/sql/vacuum_ao_stats.sql | 19 +++-------- .../test_misc/t/021_vacuum_vm_pages.pl | 7 +--- 19 files changed, 175 insertions(+), 96 deletions(-) diff --git a/contrib/pg_surgery/expected/heap_surgery.out b/contrib/pg_surgery/expected/heap_surgery.out index df7d13b0908..d9ec14824d5 100644 --- a/contrib/pg_surgery/expected/heap_surgery.out +++ b/contrib/pg_surgery/expected/heap_surgery.out @@ -175,6 +175,36 @@ DETAIL: This operation is not supported for views. select heap_force_freeze('vw'::regclass, ARRAY['(0, 1)']::tid[]); ERROR: cannot operate on relation "vw" DETAIL: This operation is not supported for views. +-- Killing tuples on a frozen page clears both VM marks exactly once. +create temp table vm_surgery (a int); +insert into vm_surgery values (1), (2); +vacuum freeze vm_surgery; +select heap_force_kill('vm_surgery'::regclass, ARRAY['(0, 1)']::tid[]); + heap_force_kill +----------------- + +(1 row) + +select heap_force_kill('vm_surgery'::regclass, ARRAY['(0, 2)']::tid[]); + heap_force_kill +----------------- + +(1 row) + +select pg_stat_force_next_flush(); + pg_stat_force_next_flush +-------------------------- + +(1 row) + +select visible_page_marks_cleared, frozen_page_marks_cleared + from pg_stat_all_tables where relid = 'vm_surgery'::regclass; + visible_page_marks_cleared | frozen_page_marks_cleared +----------------------------+--------------------------- + 1 | 1 +(1 row) + +drop table vm_surgery; -- cleanup. drop view vw; drop extension pg_surgery; diff --git a/contrib/pg_surgery/heap_surgery.c b/contrib/pg_surgery/heap_surgery.c index 88a40ab7d39..66f4a0c7495 100644 --- a/contrib/pg_surgery/heap_surgery.c +++ b/contrib/pg_surgery/heap_surgery.c @@ -264,8 +264,8 @@ heap_force_common(FunctionCallInfo fcinfo, HeapTupleForceOption heap_force_opt) if (PageIsAllVisible(page)) { PageClearAllVisible(page); - visibilitymap_clear(rel, blkno, vmbuf, - VISIBILITYMAP_VALID_BITS); + visibilitymap_clear_rel(rel, blkno, vmbuf, + VISIBILITYMAP_VALID_BITS); did_modify_vm = true; } } diff --git a/contrib/pg_surgery/sql/heap_surgery.sql b/contrib/pg_surgery/sql/heap_surgery.sql index 6526b27535d..fab0c107273 100644 --- a/contrib/pg_surgery/sql/heap_surgery.sql +++ b/contrib/pg_surgery/sql/heap_surgery.sql @@ -83,6 +83,17 @@ create view vw as select 1; select heap_force_kill('vw'::regclass, ARRAY['(0, 1)']::tid[]); select heap_force_freeze('vw'::regclass, ARRAY['(0, 1)']::tid[]); +-- Killing tuples on a frozen page clears both VM marks exactly once. +create temp table vm_surgery (a int); +insert into vm_surgery values (1), (2); +vacuum freeze vm_surgery; +select heap_force_kill('vm_surgery'::regclass, ARRAY['(0, 1)']::tid[]); +select heap_force_kill('vm_surgery'::regclass, ARRAY['(0, 2)']::tid[]); +select pg_stat_force_next_flush(); +select visible_page_marks_cleared, frozen_page_marks_cleared + from pg_stat_all_tables where relid = 'vm_surgery'::regclass; +drop table vm_surgery; + -- cleanup. drop view vw; drop extension pg_surgery; diff --git a/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml index 47b28fa18df..95dd04e902b 100644 --- a/doc/src/sgml/monitoring.sgml +++ b/doc/src/sgml/monitoring.sgml @@ -4709,7 +4709,10 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i The pg_stat_vacuum view contains one row for each database, plus one for shared objects, showing cumulative vacuum statistics - on the current instance. The current database's counters are reset + on the current instance. Elapsed and cost-delay times are rounded to the + nearest millisecond for each completed operation, index pass, or AO phase; + a sufficiently short operation can therefore contribute zero time. + The current database's counters are reset together with its other statistics by pg_stat_reset(). @@ -4736,6 +4739,8 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i the time spent waiting for segment sampling. Segment workers classify their analyze work as manual even when the coordinator starts an auto-analyze. Table failsafe counts in the summary are sums of instance-level events. + They are not divided by the number of segments for replicated tables, + since each local vacuum that enters failsafe is a separate event. <structname>pg_stat_vacuum</structname> View @@ -4836,7 +4841,10 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i are not counted. In a Cloudberry cluster the count is kept by the instance on which the vacuum failed: a vacuum dispatched to the segments that fails there is counted by - those segments, not by the coordinator. A segment reports the count + those segments, not by the coordinator. Cancellation of other segment + vacuums still executing in their table access methods also counts, so + one failed distributed command can produce several interruptions. + A segment reports the count once its part of the failed distributed transaction has ended, which may be as late as the next command of the session. diff --git a/src/backend/access/gin/ginfast.c b/src/backend/access/gin/ginfast.c index d42f9dbd5f0..be9074e47b2 100644 --- a/src/backend/access/gin/ginfast.c +++ b/src/backend/access/gin/ginfast.c @@ -49,6 +49,10 @@ typedef struct KeyArray int32 maxvalues; /* allocated size of arrays */ } KeyArray; +static void ginInsertCleanupInternal(GinState *ginstate, bool full_clean, + bool fill_fsm, bool forceCleanup, + bool is_analyze, IndexBulkDeleteResult *stats); + /* * Build a pending-list page from the given array of tuples, and write it out. @@ -467,7 +471,7 @@ ginHeapTupleFastInsert(GinState *ginstate, GinTupleCollector *collector) * pending list not forcibly. */ if (needCleanup) - ginInsertCleanup(ginstate, false, true, false, false, NULL); + ginInsertCleanup(ginstate, false, true, false, NULL); } /* @@ -777,8 +781,27 @@ processPendingPage(BuildAccumulator *accum, KeyArray *ka, */ void ginInsertCleanup(GinState *ginstate, bool full_clean, - bool fill_fsm, bool forceCleanup, bool is_analyze, + bool fill_fsm, bool forceCleanup, IndexBulkDeleteResult *stats) +{ + ginInsertCleanupInternal(ginstate, full_clean, fill_fsm, forceCleanup, + false, stats); +} + +/* + * Attribute pending-list cleanup by auto-analyze to ANALYZE progress, without + * changing the upstream ginInsertCleanup() interface used by extensions. + */ +void +ginInsertCleanupForAnalyze(GinState *ginstate, IndexBulkDeleteResult *stats) +{ + ginInsertCleanupInternal(ginstate, false, true, true, true, stats); +} + +static void +ginInsertCleanupInternal(GinState *ginstate, bool full_clean, + bool fill_fsm, bool forceCleanup, bool is_analyze, + IndexBulkDeleteResult *stats) { Relation index = ginstate->index; Buffer metabuffer, @@ -1076,7 +1099,7 @@ gin_clean_pending_list(PG_FUNCTION_ARGS) GinState ginstate; initGinState(&ginstate, indexRel); - ginInsertCleanup(&ginstate, true, true, true, false, &stats); + ginInsertCleanup(&ginstate, true, true, true, &stats); } else ereport(DEBUG1, diff --git a/src/backend/access/gin/ginvacuum.c b/src/backend/access/gin/ginvacuum.c index 00230753b06..4bcf36868d3 100644 --- a/src/backend/access/gin/ginvacuum.c +++ b/src/backend/access/gin/ginvacuum.c @@ -591,7 +591,7 @@ ginbulkdelete(IndexVacuumInfo *info, IndexBulkDeleteResult *stats, * and cleanup any pending inserts */ ginInsertCleanup(&gvs.ginstate, !IsAutoVacuumWorkerProcess(), - false, true, false, stats); + false, true, stats); } /* we'll re-count the tuples each time */ @@ -704,7 +704,7 @@ ginvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats) if (IsAutoVacuumWorkerProcess()) { initGinState(&ginstate, index); - ginInsertCleanup(&ginstate, false, true, true, true, stats); + ginInsertCleanupForAnalyze(&ginstate, stats); } return stats; } @@ -718,7 +718,7 @@ ginvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats) stats = (IndexBulkDeleteResult *) palloc0(sizeof(IndexBulkDeleteResult)); initGinState(&ginstate, index); ginInsertCleanup(&ginstate, !IsAutoVacuumWorkerProcess(), - false, true, false, stats); + false, true, stats); } memset(&idxStat, 0, sizeof(idxStat)); diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c index c3684377385..2acc4ed6bc9 100644 --- a/src/backend/access/heap/vacuumlazy.c +++ b/src/backend/access/heap/vacuumlazy.c @@ -485,6 +485,7 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, new_rel_allvisible; PGRUsage ru0; TimestampTz starttime = 0; + instr_time stats_start; PgStat_Counter startreadtime = 0, startwritetime = 0; LVExtStatCounters *extVacCounters; @@ -507,8 +508,9 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, } } - /* Used for instrumentation and stats report */ + /* Use wall time for logs and a monotonic timer for cumulative statistics. */ starttime = GetCurrentTimestamp(); + INSTR_TIME_SET_CURRENT(stats_start); startdelaytime = VacuumDelayTime; extVacCounters = extvac_stats_start(rel, verbose); @@ -796,7 +798,7 @@ heap_vacuum_rel(Relation rel, VacuumParams *params, Max(vacrel->new_live_tuples, 0), vacrel->recently_dead_tuples + vacrel->missed_dead_tuples, - starttime, + stats_start, (PgStat_Counter) rint(VacuumDelayTime - startdelaytime), VacuumFailsafeActive, vacrel->frozen_pages, vacrel->all_visible_pages); @@ -2962,9 +2964,12 @@ lazy_vacuum_one_index(Relation indrel, IndexBulkDeleteResult *istat, IndexVacuumInfo ivinfo; LVSavedErrInfo saved_err_info; LVExtStatCounters *extVacCounters; - TimestampTz istarttime = GetCurrentTimestamp(); + instr_time istarttime; + instr_time elapsed; double startdelaytime = VacuumDelayTime; + INSTR_TIME_SET_CURRENT(istarttime); + extVacCounters = extvac_stats_start(indrel, vacrel->verbose); ivinfo.index = indrel; ivinfo.heaprel = vacrel->rel; @@ -3002,9 +3007,10 @@ lazy_vacuum_one_index(Relation indrel, IndexBulkDeleteResult *istat, } /* Accumulate this pass into the index's cumulative vacuum times */ + INSTR_TIME_SET_CURRENT(elapsed); + INSTR_TIME_SUBTRACT(elapsed, istarttime); pgstat_report_index_vacuum_time(indrel, - TimestampDifferenceMilliseconds(istarttime, - GetCurrentTimestamp()), + (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)), (PgStat_Counter) rint(VacuumDelayTime - startdelaytime), IsAutoVacuumWorkerProcess()); @@ -3034,9 +3040,12 @@ lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat, IndexVacuumInfo ivinfo; LVSavedErrInfo saved_err_info; LVExtStatCounters *extVacCounters; - TimestampTz istarttime = GetCurrentTimestamp(); + instr_time istarttime; + instr_time elapsed; double startdelaytime = VacuumDelayTime; + INSTR_TIME_SET_CURRENT(istarttime); + extVacCounters = extvac_stats_start(indrel, vacrel->verbose); ivinfo.index = indrel; ivinfo.heaprel = vacrel->rel; @@ -3074,9 +3083,10 @@ lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat, } /* Accumulate this pass into the index's cumulative vacuum times */ + INSTR_TIME_SET_CURRENT(elapsed); + INSTR_TIME_SUBTRACT(elapsed, istarttime); pgstat_report_index_vacuum_time(indrel, - TimestampDifferenceMilliseconds(istarttime, - GetCurrentTimestamp()), + (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)), (PgStat_Counter) rint(VacuumDelayTime - startdelaytime), IsAutoVacuumWorkerProcess()); diff --git a/src/backend/catalog/system_views_gp_summary.sql b/src/backend/catalog/system_views_gp_summary.sql index c3bdb99b87c..4be27c0b1b4 100644 --- a/src/backend/catalog/system_views_gp_summary.sql +++ b/src/backend/catalog/system_views_gp_summary.sql @@ -185,6 +185,7 @@ FROM case when d.policytype = 'r' then (sum(total_autoanalyze_time)/d.numsegments) else sum(total_autoanalyze_time) end total_autoanalyze_time, case when d.policytype = 'r' then (sum(total_vacuum_delay_time)/d.numsegments) else sum(total_vacuum_delay_time) end total_vacuum_delay_time, case when d.policytype = 'r' then (sum(total_autovacuum_delay_time)/d.numsegments) else sum(total_autovacuum_delay_time) end total_autovacuum_delay_time, + -- Count local failsafe events even for replicated tables. sum(vacuum_failsafe_count)::bigint as vacuum_failsafe_count, case when d.policytype = 'r' then (sum(pages_frozen)/d.numsegments)::bigint else sum(pages_frozen) end pages_frozen, case when d.policytype = 'r' then (sum(pages_all_visible)/d.numsegments)::bigint else sum(pages_all_visible) end pages_all_visible, diff --git a/src/backend/commands/analyze.c b/src/backend/commands/analyze.c index 37d8c529c06..e7cf7dc56c6 100644 --- a/src/backend/commands/analyze.c +++ b/src/backend/commands/analyze.c @@ -494,6 +494,7 @@ do_analyze_rel(Relation onerel, VacuumParams *params, HeapTuple *rows; PGRUsage ru0; TimestampTz starttime = 0; + instr_time stats_start; MemoryContext caller_context; Oid save_userid; int save_sec_context; @@ -557,8 +558,9 @@ do_analyze_rel(Relation onerel, VacuumParams *params, pg_rusage_init(&ru0); } - /* Used for instrumentation and stats report */ + /* Use wall time for logs and a monotonic timer for cumulative statistics. */ starttime = GetCurrentTimestamp(); + INSTR_TIME_SET_CURRENT(stats_start); /* * Determine which columns to analyze @@ -1228,9 +1230,9 @@ do_analyze_rel(Relation onerel, VacuumParams *params, */ if (!inh) pgstat_report_analyze(onerel, totalrows, totaldeadrows, - (va_cols == NIL), starttime); + (va_cols == NIL), stats_start); else if (onerel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE) - pgstat_report_analyze(onerel, 0, 0, (va_cols == NIL), starttime); + pgstat_report_analyze(onerel, 0, 0, (va_cols == NIL), stats_start); /* * If this isn't part of VACUUM ANALYZE, let index AMs do cleanup. diff --git a/src/backend/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c index 9758759f82c..db4d5ea9efb 100644 --- a/src/backend/commands/vacuum_ao.c +++ b/src/backend/commands/vacuum_ao.c @@ -171,7 +171,7 @@ static void ao_accum_resources(PgStat_CommonCounts *dst, static void ao_measure_index_resources(Relation indrel, LVExtStatCounters *counters, AOVacuumRelStats *vacrelstats, bool verbose); -static void ao_report_index_vacuum_time(Relation indrel, TimestampTz starttime, +static void ao_report_index_vacuum_time(Relation indrel, instr_time starttime, double startdelaytime); static void @@ -675,12 +675,15 @@ ao_measure_index_resources(Relation indrel, LVExtStatCounters *counters, * lazy_vacuum_one_index() and lazy_cleanup_one_index(). */ static void -ao_report_index_vacuum_time(Relation indrel, TimestampTz starttime, +ao_report_index_vacuum_time(Relation indrel, instr_time starttime, double startdelaytime) { + instr_time elapsed; + + INSTR_TIME_SET_CURRENT(elapsed); + INSTR_TIME_SUBTRACT(elapsed, starttime); pgstat_report_index_vacuum_time(indrel, - TimestampDifferenceMilliseconds(starttime, - GetCurrentTimestamp()), + (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)), (PgStat_Counter) rint(VacuumDelayTime - startdelaytime), IsAutoVacuumWorkerProcess()); @@ -792,11 +795,12 @@ vacuum_appendonly_indexes(Relation aoRelation, int options, Bitmapset *dead_segs { for (i = 0; i < nindexes; i++) { - TimestampTz istarttime = GetCurrentTimestamp(); + instr_time istarttime; double startdelaytime = VacuumDelayTime; LVExtStatCounters *extcounters; + INSTR_TIME_SET_CURRENT(istarttime); extcounters = extvac_stats_start(Irel[i], elevel == INFO); scan_index(Irel[i], aoRelation, @@ -813,11 +817,12 @@ vacuum_appendonly_indexes(Relation aoRelation, int options, Bitmapset *dead_segs { for (i = 0; i < nindexes; i++) { - TimestampTz istarttime = GetCurrentTimestamp(); + instr_time istarttime; double startdelaytime = VacuumDelayTime; LVExtStatCounters *extcounters; + INSTR_TIME_SET_CURRENT(istarttime); extcounters = extvac_stats_start(Irel[i], elevel == INFO); vacuum_appendonly_index(Irel[i], aoRelation, diff --git a/src/backend/commands/vacuumparallel.c b/src/backend/commands/vacuumparallel.c index 078b7bd97d3..1fad768ecd9 100644 --- a/src/backend/commands/vacuumparallel.c +++ b/src/backend/commands/vacuumparallel.c @@ -835,6 +835,9 @@ parallel_vacuum_process_unsafe_indexes(ParallelVacuumState *pvs) * process. After vacuuming the index this function copies the index * statistics returned from ambulkdelete and amvacuumcleanup to the DSM * segment. + * + * Currently unreachable in Cloudberry (see dead_items_alloc()); keep timing + * aligned with the serial path for when parallel index vacuum is enabled. */ static void parallel_vacuum_process_one_index(ParallelVacuumState *pvs, Relation indrel, @@ -844,9 +847,12 @@ parallel_vacuum_process_one_index(ParallelVacuumState *pvs, Relation indrel, IndexBulkDeleteResult *istat_res; IndexVacuumInfo ivinfo; LVExtStatCounters *extVacCounters; - TimestampTz istarttime = GetCurrentTimestamp(); + instr_time istarttime; + instr_time elapsed; double startdelaytime = VacuumDelayTime; + INSTR_TIME_SET_CURRENT(istarttime); + /* * Update the pointer to the corresponding bulk-deletion result if someone * has already updated it @@ -900,9 +906,10 @@ parallel_vacuum_process_one_index(ParallelVacuumState *pvs, Relation indrel, * leader's DSM flag to classify autovacuum: a parallel worker of an * autovacuum leader is a regular background worker. */ + INSTR_TIME_SET_CURRENT(elapsed); + INSTR_TIME_SUBTRACT(elapsed, istarttime); pgstat_report_index_vacuum_time(indrel, - TimestampDifferenceMilliseconds(istarttime, - GetCurrentTimestamp()), + (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)), (PgStat_Counter) rint(VacuumDelayTime - startdelaytime), pvs->shared->is_autovacuum); diff --git a/src/backend/utils/activity/pgstat_relation.c b/src/backend/utils/activity/pgstat_relation.c index fd42ae3cceb..96f0cd4b596 100644 --- a/src/backend/utils/activity/pgstat_relation.c +++ b/src/backend/utils/activity/pgstat_relation.c @@ -17,6 +17,8 @@ #include "postgres.h" +#include + #include "access/twophase_rmgr.h" #include "access/xact.h" #include "catalog/partition.h" @@ -216,13 +218,16 @@ pgstat_drop_relation(Relation rel) void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, - TimestampTz starttime, PgStat_Counter delaytime, + instr_time starttime, PgStat_Counter delaytime, bool failsafe, PgStat_Counter pages_frozen, PgStat_Counter pages_all_visible) { + instr_time elapsed; + + INSTR_TIME_SET_CURRENT(elapsed); + INSTR_TIME_SUBTRACT(elapsed, starttime); pgstat_report_vacuum_elapsed(tableoid, shared, livetuples, deadtuples, - TimestampDifferenceMilliseconds(starttime, - GetCurrentTimestamp()), + (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)), delaytime, failsafe, pages_frozen, pages_all_visible, true); } @@ -391,7 +396,7 @@ pgstat_report_index_vacuum_time(Relation rel, PgStat_Counter elapsedtime, void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, - bool resetcounter, TimestampTz starttime) + bool resetcounter, instr_time starttime) { PgStat_EntryRef *entry_ref; PgStatShared_Relation *shtabentry; @@ -399,6 +404,7 @@ pgstat_report_analyze(Relation rel, Oid dboid = (rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId); TimestampTz ts; PgStat_Counter elapsedtime; + instr_time elapsed; if (!pgstat_track_counts) return; @@ -434,7 +440,9 @@ pgstat_report_analyze(Relation rel, /* Store the data in the table's hash table entry. */ ts = GetCurrentTimestamp(); - elapsedtime = TimestampDifferenceMilliseconds(starttime, ts); + INSTR_TIME_SET_CURRENT(elapsed); + INSTR_TIME_SUBTRACT(elapsed, starttime); + elapsedtime = (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)); /* block acquiring lock for the same reason as pgstat_report_autovac() */ entry_ref = pgstat_get_entry_ref_locked(PGSTAT_KIND_RELATION, dboid, diff --git a/src/include/access/gin_private.h b/src/include/access/gin_private.h index 3f205aa269a..549254bf4e3 100644 --- a/src/include/access/gin_private.h +++ b/src/include/access/gin_private.h @@ -464,8 +464,10 @@ extern void ginHeapTupleFastCollect(GinState *ginstate, OffsetNumber attnum, Datum value, bool isNull, ItemPointer ht_ctid); extern void ginInsertCleanup(GinState *ginstate, bool full_clean, - bool fill_fsm, bool forceCleanup, bool is_analyze, + bool fill_fsm, bool forceCleanup, IndexBulkDeleteResult *stats); +extern void ginInsertCleanupForAnalyze(GinState *ginstate, + IndexBulkDeleteResult *stats); /* ginpostinglist.c */ diff --git a/src/include/pgstat.h b/src/include/pgstat.h index a315fbd7238..7d1816e226d 100644 --- a/src/include/pgstat.h +++ b/src/include/pgstat.h @@ -704,7 +704,7 @@ extern void pgstat_report_vacuum_elapsed(Oid tableoid, bool shared, PgStat_Counter pages_all_visible, bool is_complete); extern void pgstat_report_vacuum(Oid tableoid, bool shared, PgStat_Counter livetuples, PgStat_Counter deadtuples, - TimestampTz starttime, PgStat_Counter delaytime, + instr_time starttime, PgStat_Counter delaytime, bool failsafe, PgStat_Counter pages_frozen, PgStat_Counter pages_all_visible); extern void pgstat_report_index_vacuum_time(Relation rel, @@ -714,7 +714,7 @@ extern void pgstat_report_index_vacuum_time(Relation rel, extern void pgstat_count_vacuum_error(bool shared); extern void pgstat_report_analyze(Relation rel, PgStat_Counter livetuples, PgStat_Counter deadtuples, - bool resetcounter, TimestampTz starttime); + bool resetcounter, instr_time starttime); /* * If stats are enabled, but pending data hasn't been prepared yet, call diff --git a/src/test/isolation2/expected/vacuum_analyze_stats.out b/src/test/isolation2/expected/vacuum_analyze_stats.out index c41756b5908..e0e5561d1cb 100644 --- a/src/test/isolation2/expected/vacuum_analyze_stats.out +++ b/src/test/isolation2/expected/vacuum_analyze_stats.out @@ -77,15 +77,9 @@ SELECT wait_for_analyze_times(); ------------------------ t (1 row) -SELECT count(*) = 2 AND bool_and(s.analyze_count = 0 AND s.autoanalyze_count > 0 AND s.total_analyze_time = 0 AND s.total_autoanalyze_time > 0 AND s.total_autoanalyze_time = q.total_autoanalyze_time) AS auto_times_match FROM gp_stat_all_tables_summary s JOIN pg_stat_all_tables q USING (relid) WHERE s.relname IN ('analyze_time_hash', 'analyze_time_repl'); - auto_times_match ------------------- - t -(1 row) -DROP FUNCTION wait_for_analyze_times(); -DROP -DROP TABLE analyze_time_hash, analyze_time_repl; -DROP +-- Restore coordinator settings immediately after the wait. The isolation2 +-- executor continues after SQL errors, including the timeout above, so these +-- commands also run when auto-analyze did not finish in time. ALTER SYSTEM RESET autovacuum; ALTER ALTER SYSTEM RESET autovacuum_naptime; @@ -95,5 +89,14 @@ SELECT pg_reload_conf(); ---------------- t (1 row) +SELECT count(*) = 2 AND bool_and(s.analyze_count = 0 AND s.autoanalyze_count > 0 AND s.total_analyze_time = 0 AND s.total_autoanalyze_time > 0 AND s.total_autoanalyze_time = q.total_autoanalyze_time) AS auto_times_match FROM gp_stat_all_tables_summary s JOIN pg_stat_all_tables q USING (relid) WHERE s.relname IN ('analyze_time_hash', 'analyze_time_repl'); + auto_times_match +------------------ + t +(1 row) +DROP FUNCTION wait_for_analyze_times(); +DROP +DROP TABLE analyze_time_hash, analyze_time_repl; +DROP RESET gp_autostats_mode; RESET diff --git a/src/test/isolation2/expected/vacuum_ao_stats.out b/src/test/isolation2/expected/vacuum_ao_stats.out index 08f5be81186..4a08706a8e5 100644 --- a/src/test/isolation2/expected/vacuum_ao_stats.out +++ b/src/test/isolation2/expected/vacuum_ao_stats.out @@ -122,28 +122,10 @@ ERROR: fault triggered, fault name:'vacuum_ao_after_compact' fault type:'error' Success: (3 rows) --- The phases of an append-optimized vacuum share one AOVacuumRelStats, which --- is freed at the end of the last phase. A vacuum that fails in between used --- to leave it behind, and the next vacuum of the relation then reused its --- start time, so the time of everything that happened in between was added --- to the relation's cumulative vacuum time. Let time pass. -1: SELECT pg_sleep(5); - pg_sleep ----------- - -(1 row) - +-- Finish a successful vacuum after the failed distributed transaction. 1: VACUUM vacstat_ao_row; VACUUM --- The second vacuum takes milliseconds; without resetting the stats of the --- failed one it would be credited with the five seconds slept above. -1: SELECT sum(total_vacuum_time) < 3000 AS vacuum_time_is_sane FROM gp_dist_random('pg_stat_all_tables') WHERE relname = 'vacstat_ao_row'; - vacuum_time_is_sane ---------------------- - t -(1 row) - -- The segments that raised the error counted it; the coordinator, which only -- dispatched the failing phase, did not. A segment may also be canceled -- after its phase is already done, so check for "some", not for "all". @@ -151,12 +133,12 @@ VACUUM -- A segment adds the count to its pending statistics when its transaction -- ends, and flushes them when it is idle outside a transaction, which it is -- not while its part of the failed distributed transaction waits for the --- coordinator; the second vacuum above has ended that. Give the flush the --- second it may wait for (PGSTAT_MIN_INTERVAL). -1: SELECT pg_sleep(2); - pg_sleep ----------- - +-- coordinator; the second vacuum above has ended that. Force the next flush +-- on every instance instead of waiting for PGSTAT_MIN_INTERVAL. +1: SELECT gp_stat_force_next_flush(); + gp_stat_force_next_flush +-------------------------- + (1 row) 1: SELECT gp_segment_id = -1 AS coordinator, sum(vacuum_interrupt_count) > 0 AS interrupted FROM gp_stat_vacuum WHERE datname = current_database() GROUP BY 1 ORDER BY 1; coordinator | interrupted diff --git a/src/test/isolation2/sql/vacuum_analyze_stats.sql b/src/test/isolation2/sql/vacuum_analyze_stats.sql index bb7c6e9c245..2ffdacb52c1 100644 --- a/src/test/isolation2/sql/vacuum_analyze_stats.sql +++ b/src/test/isolation2/sql/vacuum_analyze_stats.sql @@ -60,6 +60,12 @@ BEGIN END; /* in func */ $$; SELECT wait_for_analyze_times(); +-- Restore coordinator settings immediately after the wait. The isolation2 +-- executor continues after SQL errors, including the timeout above, so these +-- commands also run when auto-analyze did not finish in time. +ALTER SYSTEM RESET autovacuum; +ALTER SYSTEM RESET autovacuum_naptime; +SELECT pg_reload_conf(); SELECT count(*) = 2 AND bool_and(s.analyze_count = 0 AND s.autoanalyze_count > 0 AND s.total_analyze_time = 0 AND s.total_autoanalyze_time > 0 AND s.total_autoanalyze_time = q.total_autoanalyze_time) AS auto_times_match @@ -67,7 +73,4 @@ SELECT count(*) = 2 AND bool_and(s.analyze_count = 0 AND s.autoanalyze_count > 0 WHERE s.relname IN ('analyze_time_hash', 'analyze_time_repl'); DROP FUNCTION wait_for_analyze_times(); DROP TABLE analyze_time_hash, analyze_time_repl; -ALTER SYSTEM RESET autovacuum; -ALTER SYSTEM RESET autovacuum_naptime; -SELECT pg_reload_conf(); RESET gp_autostats_mode; diff --git a/src/test/isolation2/sql/vacuum_ao_stats.sql b/src/test/isolation2/sql/vacuum_ao_stats.sql index b6413a383df..d691a7983d9 100644 --- a/src/test/isolation2/sql/vacuum_ao_stats.sql +++ b/src/test/isolation2/sql/vacuum_ao_stats.sql @@ -72,20 +72,9 @@ DELETE FROM vacstat_ao_row WHERE i % 2 = 1; 1: SELECT gp_inject_fault('vacuum_ao_after_compact', 'reset', dbid) FROM gp_segment_configuration WHERE role = 'p' AND content > -1; --- The phases of an append-optimized vacuum share one AOVacuumRelStats, which --- is freed at the end of the last phase. A vacuum that fails in between used --- to leave it behind, and the next vacuum of the relation then reused its --- start time, so the time of everything that happened in between was added --- to the relation's cumulative vacuum time. Let time pass. -1: SELECT pg_sleep(5); - +-- Finish a successful vacuum after the failed distributed transaction. 1: VACUUM vacstat_ao_row; --- The second vacuum takes milliseconds; without resetting the stats of the --- failed one it would be credited with the five seconds slept above. -1: SELECT sum(total_vacuum_time) < 3000 AS vacuum_time_is_sane - FROM gp_dist_random('pg_stat_all_tables') WHERE relname = 'vacstat_ao_row'; - -- The segments that raised the error counted it; the coordinator, which only -- dispatched the failing phase, did not. A segment may also be canceled -- after its phase is already done, so check for "some", not for "all". @@ -93,9 +82,9 @@ DELETE FROM vacstat_ao_row WHERE i % 2 = 1; -- A segment adds the count to its pending statistics when its transaction -- ends, and flushes them when it is idle outside a transaction, which it is -- not while its part of the failed distributed transaction waits for the --- coordinator; the second vacuum above has ended that. Give the flush the --- second it may wait for (PGSTAT_MIN_INTERVAL). -1: SELECT pg_sleep(2); +-- coordinator; the second vacuum above has ended that. Force the next flush +-- on every instance instead of waiting for PGSTAT_MIN_INTERVAL. +1: SELECT gp_stat_force_next_flush(); 1: SELECT gp_segment_id = -1 AS coordinator, sum(vacuum_interrupt_count) > 0 AS interrupted FROM gp_stat_vacuum WHERE datname = current_database() diff --git a/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl b/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl index 7e05fb36d36..fff04b68e3e 100644 --- a/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl +++ b/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl @@ -14,7 +14,7 @@ # implied. See the License for the specific language governing # permissions and limitations under the License. -# Completed-vacuum work is cumulative and does not require relallfrozen. +# Completed-vacuum work is cumulative. use strict; use warnings FATAL => 'all'; use PostgreSQL::Test::Cluster; @@ -58,10 +58,5 @@ SELECT pages_frozen = 0 AND pages_all_visible = 0 FROM pg_stat_all_tables WHERE relid = 'vm_pages'::regclass }), 't', 'relation statistics reset clears both work counters'); -is($node->safe_psql('postgres', q{ -SELECT NOT EXISTS (SELECT FROM pg_attribute - WHERE attrelid = 'pg_class'::regclass - AND attname = 'relallfrozen') -}), 't', 'no relallfrozen catalog field is required'); $node->stop; done_testing();