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/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/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/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/doc/src/sgml/monitoring.sgml b/doc/src/sgml/monitoring.sgml
index f9ceead292f..95dd04e902b 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,166 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i
+
+ pg_stat_vacuum
+ 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. 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().
+
+
+ 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.
+ They are not divided by the number of segments for replicated tables,
+ since each local vacuum that enters failsafe is a separate event.
+
+
+ pg_stat_vacuum View
+
+
+
+
+ Column Type
+
+
+ Description
+
+
+
+
+
+
+ datidoid
+
+
+ OID of this database, or 0 for objects belonging to a shared
+ relation
+
+
+
+
+
+ datnamename
+
+
+ Name of this database, or NULL for shared
+ objects.
+
+
+
+
+
+ total_vacuum_timedouble 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_timedouble precision
+
+
+ Total time the autovacuum daemon spent processing tables of this
+ database, in milliseconds
+
+
+
+
+
+ total_vacuum_delay_timedouble 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_timedouble precision
+
+
+ Total time autovacuums of this database spent sleeping in cost-based
+ delay points, in milliseconds (counted only when
+ is enabled)
+
+
+
+
+
+ vacuum_failsafe_countbigint
+
+
+ Number of vacuums in this database that entered the wraparound
+ failsafe mode (see )
+
+
+
+
+
+ vacuum_interrupt_countbigint
+
+
+ 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. 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.
+
+
+
+
+
+ stats_resettimestamp with time zone
+
+
+ Time at which these statistics were last reset
+
+
+
+
+
+
+
pg_stat_database_conflicts
@@ -4926,6 +5092,62 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i
+
+
+ total_vacuum_timedouble 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_timedouble 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_timedouble 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_timedouble 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_countbigint
+
+
+ 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_insbigint
@@ -5017,6 +5239,60 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i
+
+
+
+
+ pages_frozenbigint
+
+ 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.
+
+
+
+
+
+ pages_all_visiblebigint
+
+ 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_clearedbigint
+
+
+ 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_clearedbigint
+
+
+ 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_vacuumtimestamp with time zone
@@ -5094,6 +5370,66 @@ SELECT pid, wait_event_type, wait_event FROM pg_stat_activity WHERE wait_event i
daemon
+
+
+
+ total_vacuum_timedouble precision
+
+
+ Total time this table has been manually vacuumed, in milliseconds
+
+
+
+
+
+ total_autovacuum_timedouble precision
+
+
+ Total time this table has been vacuumed by the autovacuum daemon,
+ in milliseconds
+
+
+
+
+
+ total_analyze_timedouble precision
+
+
+ Total time this table has been manually analyzed, in milliseconds
+
+
+
+
+
+ total_autoanalyze_timedouble precision
+
+
+ Total time this table has been analyzed by the autovacuum daemon,
+ in milliseconds
+
+
+
+
+
+ total_vacuum_delay_timedouble precision
+
+
+ Total time this table's vacuums spent sleeping in cost-based delay
+ points, in milliseconds (counted only when
+ is enabled)
+
+
+
+
+
+ total_autovacuum_delay_timedouble precision
+
+
+ Total time autovacuums of this table spent sleeping in cost-based
+ delay points, in milliseconds (counted only when
+ is enabled)
+
+
@@ -6370,6 +6706,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.
+
+
pg_stat_progress_analyze View
@@ -6496,6 +6839,18 @@ FROM pg_stat_get_backend_idset() AS backendid;
acquiring inherited sample rows.
+
+
+
+ delay_timedouble precision
+
+
+ Total time spent sleeping due to cost-based delay (see
+ , in milliseconds
+ (if is enabled, otherwise
+ zero).
+
+
@@ -7252,6 +7607,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.
+
+
pg_stat_progress_vacuum View
@@ -7377,6 +7739,18 @@ FROM pg_stat_get_backend_idset() AS backendid;
Number of dead tuples collected since the last index vacuum cycle.
+
+
+
+ delay_timedouble precision
+
+
+ Total time spent sleeping due to cost-based delay (see
+ ), in milliseconds
+ (if is enabled, otherwise
+ zero).
+
+
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..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.
@@ -779,6 +783,25 @@ void
ginInsertCleanup(GinState *ginstate, bool full_clean,
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,
@@ -891,7 +914,7 @@ ginInsertCleanup(GinState *ginstate, bool full_clean,
*/
processPendingPage(&accum, &datums, page, FirstOffsetNumber);
- vacuum_delay_point();
+ vacuum_delay_point(is_analyze);
/*
* Is it time to flush memory to disk? Flush if we are at the end of
@@ -928,7 +951,7 @@ ginInsertCleanup(GinState *ginstate, bool full_clean,
{
ginEntryInsert(ginstate, attnum, key, category,
list, nlist, NULL);
- vacuum_delay_point();
+ vacuum_delay_point(is_analyze);
}
/*
@@ -1001,7 +1024,7 @@ ginInsertCleanup(GinState *ginstate, bool full_clean,
/*
* Read next page in pending list
*/
- vacuum_delay_point();
+ vacuum_delay_point(is_analyze);
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..4bcf36868d3 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 */
@@ -704,7 +704,7 @@ ginvacuumcleanup(IndexVacuumInfo *info, IndexBulkDeleteResult *stats)
if (IsAutoVacuumWorkerProcess())
{
initGinState(&ginstate, index);
- ginInsertCleanup(&ginstate, false, true, true, stats);
+ ginInsertCleanupForAnalyze(&ginstate, stats);
}
return stats;
}
@@ -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/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 cf97d85df5d..2acc4ed6bc9 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 */
@@ -484,9 +485,11 @@ 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;
+ double startdelaytime;
WalUsage startwalusage = pgWalUsage;
BufferUsage startbufferusage = pgBufferUsage;
ErrorContextCallback errcallback;
@@ -498,7 +501,6 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
if (instrument)
{
pg_rusage_init(&ru0);
- starttime = GetCurrentTimestamp();
if (track_io_timing)
{
startreadtime = pgStatBlockReadTime;
@@ -506,6 +508,10 @@ heap_vacuum_rel(Relation rel, VacuumParams *params,
}
}
+ /* 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);
pgstat_progress_start_command(PROGRESS_COMMAND_VACUUM,
@@ -593,6 +599,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;
@@ -779,11 +786,22 @@ 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);
+ vacrel->missed_dead_tuples,
+ stats_start,
+ (PgStat_Counter) rint(VacuumDelayTime - startdelaytime),
+ VacuumFailsafeActive, vacrel->frozen_pages,
+ vacrel->all_visible_pages);
pgstat_progress_end_command();
if (instrument)
@@ -882,6 +900,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 :
@@ -918,8 +938,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,
@@ -1075,7 +1096,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.
@@ -1299,6 +1320,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);
@@ -1315,7 +1339,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);
}
@@ -1340,7 +1364,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);
}
@@ -1372,6 +1396,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 |
@@ -1538,7 +1564,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++;
}
@@ -1661,6 +1687,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 */
@@ -2641,7 +2670,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;
@@ -2797,6 +2826,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);
}
@@ -2933,6 +2964,11 @@ lazy_vacuum_one_index(Relation indrel, IndexBulkDeleteResult *istat,
IndexVacuumInfo ivinfo;
LVSavedErrInfo saved_err_info;
LVExtStatCounters *extVacCounters;
+ instr_time istarttime;
+ instr_time elapsed;
+ double startdelaytime = VacuumDelayTime;
+
+ INSTR_TIME_SET_CURRENT(istarttime);
extVacCounters = extvac_stats_start(indrel, vacrel->verbose);
ivinfo.index = indrel;
@@ -2970,6 +3006,15 @@ lazy_vacuum_one_index(Relation indrel, IndexBulkDeleteResult *istat,
pfree(extVacCounters);
}
+ /* 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,
+ (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)),
+ (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);
@@ -2995,6 +3040,11 @@ lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat,
IndexVacuumInfo ivinfo;
LVSavedErrInfo saved_err_info;
LVExtStatCounters *extVacCounters;
+ instr_time istarttime;
+ instr_time elapsed;
+ double startdelaytime = VacuumDelayTime;
+
+ INSTR_TIME_SET_CURRENT(istarttime);
extVacCounters = extvac_stats_start(indrel, vacrel->verbose);
ivinfo.index = indrel;
@@ -3032,6 +3082,15 @@ lazy_cleanup_one_index(Relation indrel, IndexBulkDeleteResult *istat,
pfree(extVacCounters);
}
+ /* 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,
+ (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)),
+ (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/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/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/catalog/system_views.sql b/src/backend/catalog/system_views.sql
index 24b7fc1d33b..e49d1baad4f 100644
--- a/src/backend/catalog/system_views.sql
+++ b/src/backend/catalog/system_views.sql
@@ -701,7 +701,18 @@ 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_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
pg_index I ON C.oid = I.indrelid
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
@@ -821,7 +832,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 +1220,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 +1597,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 +1619,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 +1968,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..4be27c0b1b4 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,18 @@ 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.pages_frozen,
+ m.pages_all_visible,
+ m.visible_page_marks_cleared,
+ m.frozen_page_marks_cleared
FROM
(SELECT
allt.relid,
@@ -148,7 +178,20 @@ 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,
+ -- 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,
+
+ 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 +272,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 +287,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 +310,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 +464,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 +476,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 +486,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 +498,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/commands/analyze.c b/src/backend/commands/analyze.c
index 194f49ee164..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;
@@ -542,7 +543,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 +556,12 @@ do_analyze_rel(Relation onerel, VacuumParams *params,
}
pg_rusage_init(&ru0);
- starttime = GetCurrentTimestamp();
}
+ /* 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
*
@@ -1223,9 +1230,9 @@ do_analyze_rel(Relation onerel, VacuumParams *params,
*/
if (!inh)
pgstat_report_analyze(onerel, totalrows, totaldeadrows,
- (va_cols == NIL));
+ (va_cols == NIL), stats_start);
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), stats_start);
/*
* If this isn't part of VACUUM ANALYZE, let index AMs do cleanup.
@@ -1424,7 +1431,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
@@ -1844,7 +1851,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);
@@ -3482,7 +3489,7 @@ compute_trivial_stats(VacAttrStatsP stats,
Datum value;
bool isnull;
- vacuum_delay_point();
+ vacuum_delay_point(true);
value = fetchfunc(stats, i, &isnull);
@@ -3604,7 +3611,7 @@ compute_distinct_stats(VacAttrStatsP stats,
int firstcount1,
j;
- vacuum_delay_point();
+ vacuum_delay_point(true);
value = fetchfunc(stats, i, &isnull);
@@ -3964,7 +3971,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..e29aed054d3 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
@@ -116,6 +118,13 @@ int vacuum_multixact_failsafe_age;
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.
@@ -2881,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))
@@ -3146,7 +3173,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;
@@ -3189,13 +3216,37 @@ vacuum_delay_point(void)
/* 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)
+ VacuumDelayTime += INSTR_TIME_GET_MILLISEC(delay);
+
+ 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/commands/vacuum_ao.c b/src/backend/commands/vacuum_ao.c
index 49503087aa9..db4d5ea9efb 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_report_index_vacuum_time(Relation indrel, instr_time 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,11 +312,9 @@ ao_vacuum_rel_post_cleanup(Relation onerel, VacuumParams *params, BufferAccessSt
false,
true /* isvacuum */);
- /* report results to the stats collector, too */
- pgstat_report_vacuum(RelationGetRelid(onerel),
- onerel->rd_rel->relisshared,
- reltuples,
- deadtuples);
+ /* Report once all phase timers have been stopped. */
+ vacrelstats->live_tuples = reltuples;
+ vacrelstats->dead_tuples = deadtuples;
SIMPLE_FAULT_INJECTOR("vacuum_ao_post_cleanup_end");
}
@@ -439,6 +441,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);
@@ -484,6 +489,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
*/
@@ -522,6 +530,26 @@ 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);
+
+ /*
+ * 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, 0, 0, /* AO has no failsafe mode or heap VM. */
+ ao_vacuum_phase == VACOPT_AO_POST_CLEANUP_PHASE);
+ }
+
if (ao_vacuum_phase == VACOPT_AO_POST_CLEANUP_PHASE)
{
pgstat_progress_end_command();
@@ -641,6 +669,26 @@ 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_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,
+ (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)),
+ (PgStat_Counter) rint(VacuumDelayTime -
+ startdelaytime),
+ IsAutoVacuumWorkerProcess());
+}
+
/*
* Recycling AWAITING_DROP segments.
*/
@@ -715,6 +763,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));
@@ -745,8 +795,12 @@ vacuum_appendonly_indexes(Relation aoRelation, int options, Bitmapset *dead_segs
{
for (i = 0; i < nindexes; i++)
{
+ 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,
@@ -756,14 +810,19 @@ 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_report_index_vacuum_time(Irel[i], istarttime, startdelaytime);
}
}
else
{
for (i = 0; i < nindexes; i++)
{
+ 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,
@@ -775,13 +834,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_report_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;
}
@@ -899,7 +959,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/backend/commands/vacuumparallel.c b/src/backend/commands/vacuumparallel.c
index de2cb9c0dba..1fad768ecd9 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) ?
@@ -828,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,
@@ -837,6 +847,11 @@ parallel_vacuum_process_one_index(ParallelVacuumState *pvs, Relation indrel,
IndexBulkDeleteResult *istat_res;
IndexVacuumInfo ivinfo;
LVExtStatCounters *extVacCounters;
+ 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
@@ -886,6 +901,19 @@ 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.
+ */
+ INSTR_TIME_SET_CURRENT(elapsed);
+ INSTR_TIME_SUBTRACT(elapsed, istarttime);
+ pgstat_report_index_vacuum_time(indrel,
+ (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)),
+ (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/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/activity/pgstat_database.c b/src/backend/utils/activity/pgstat_database.c
index 813aa359fa0..129531516e2 100644
--- a/src/backend/utils/activity/pgstat_database.c
+++ b/src/backend/utils/activity/pgstat_database.c
@@ -36,6 +36,13 @@ static int pgStatXactCommit = 0;
static int pgStatXactRollback = 0;
static PgStat_Counter pgLastSessionReportTime = 0;
+/*
+ * 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;
+static PgStat_Counter pgStatSharedVacuumErrors = 0;
+
/*
* Remove entry for the database being dropped.
@@ -245,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)
{
@@ -260,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);
}
/*
@@ -326,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 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.
+ *
+ * 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.
*/
@@ -417,6 +472,12 @@ 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(vacuum_failsafe_count);
+ PGSTAT_ACCUM_DBCOUNT(vacuum_interrupt_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 45bbf9abcb7..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"
@@ -215,7 +217,32 @@ 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,
+ 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,
+ (PgStat_Counter) rint(INSTR_TIME_GET_MILLISEC(elapsed)),
+ delaytime, failsafe, pages_frozen, pages_all_visible, 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, PgStat_Counter pages_frozen,
+ PgStat_Counter pages_all_visible, bool is_complete)
{
PgStat_EntryRef *entry_ref;
PgStatShared_Relation *shtabentry;
@@ -236,34 +263,78 @@ 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;
}
+ tabentry->pages_frozen += pages_frozen;
+ tabentry->pages_all_visible += pages_all_visible;
+
+ if (failsafe)
+ tabentry->vacuum_failsafe_count++;
+
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;
+ }
+
+ if (failsafe)
+ dbentry->vacuum_failsafe_count++;
+ }
+
/*
* Flush IO statistics now. pgstat_report_stat() will flush IO stats,
* however this will not be called until after an entire autovacuum cycle
@@ -273,6 +344,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.
*
@@ -282,12 +396,15 @@ pgstat_report_vacuum(Oid tableoid, bool shared,
void
pgstat_report_analyze(Relation rel,
PgStat_Counter livetuples, PgStat_Counter deadtuples,
- bool resetcounter)
+ bool resetcounter, instr_time starttime)
{
PgStat_EntryRef *entry_ref;
PgStatShared_Relation *shtabentry;
PgStat_StatTabEntry *tabentry;
Oid dboid = (rel->rd_rel->relisshared ? InvalidOid : MyDatabaseId);
+ TimestampTz ts;
+ PgStat_Counter elapsedtime;
+ instr_time elapsed;
if (!pgstat_track_counts)
return;
@@ -321,6 +438,12 @@ pgstat_report_analyze(Relation rel,
deadtuples = Max(deadtuples, 0);
}
+ /* Store the data in the table's hash table entry. */
+ ts = GetCurrentTimestamp();
+ 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,
RelationGetRelid(rel),
@@ -344,13 +467,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);
@@ -834,6 +959,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/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/pgstatfuncs.c b/src/backend/utils/adt/pgstatfuncs.c
index 777ac00a340..a9e3f66a8a9 100644
--- a/src/backend/utils/adt/pgstatfuncs.c
+++ b/src/backend/utils/adt/pgstatfuncs.c
@@ -120,6 +120,51 @@ 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_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)
+
+/* 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 +1144,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 +1296,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/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/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/access/appendonly_compaction.h b/src/include/access/appendonly_compaction.h
index 83746b406ef..52e8bd04a74 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"
@@ -36,9 +37,12 @@ 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 */
+ 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. */
diff --git a/src/include/access/gin_private.h b/src/include/access/gin_private.h
index 0aafe650c28..549254bf4e3 100644
--- a/src/include/access/gin_private.h
+++ b/src/include/access/gin_private.h
@@ -464,7 +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, IndexBulkDeleteResult *stats);
+ bool fill_fsm, bool forceCleanup,
+ IndexBulkDeleteResult *stats);
+extern void ginInsertCleanupForAnalyze(GinState *ginstate,
+ IndexBulkDeleteResult *stats);
/* ginpostinglist.c */
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/catalog/catversion.h b/src/include/catalog/catversion.h
index c0dc421c3e0..287ec7c0f01 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 302611241
#endif
diff --git a/src/include/catalog/pg_proc.dat b/src/include/catalog/pg_proc.dat
index 8451447907d..1654b79c719 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',
@@ -13019,3 +13083,12 @@
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' },
+{ 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/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 f19205c584a..08669efeeab 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,8 @@ 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);
extern void vacuum(List *relations, VacuumParams *params,
@@ -494,7 +497,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,
diff --git a/src/include/pgstat.h b/src/include/pgstat.h
index 680b288ecdd..7d1816e226d 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 0x01A5BCC0
+#define PGSTAT_FILE_FORMAT_ID 0x01A5BCC1
typedef struct PgStat_ArchiverStats
{
@@ -349,6 +357,26 @@ 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;
+
+ /*
+ * Number of vacuums in this database that entered the wraparound
+ * failsafe mode (see vacuum_failsafe_age).
+ */
+ PgStat_Counter vacuum_failsafe_count;
+
+ /* # of vacuums in this database interrupted by errors */
+ PgStat_Counter vacuum_interrupt_count;
+
TimestampTz stat_reset_timestamp;
} PgStat_StatDBEntry;
@@ -413,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;
@@ -422,6 +452,28 @@ 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;
+
+ /*
+ * 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;
+
+ /*
+ * Number of vacuums of this relation that entered the wraparound
+ * 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_Counter pages_all_visible;
} PgStat_StatTabEntry;
typedef struct PgStat_WalStats
@@ -645,12 +697,24 @@ 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, 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);
-
+ PgStat_Counter livetuples, PgStat_Counter deadtuples,
+ 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,
+ 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);
+ bool resetcounter, instr_time starttime);
/*
* If stats are enabled, but pending data hasn't been prepared yet, call
@@ -699,6 +763,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);
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",
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..a902779d9ab
--- /dev/null
+++ b/src/test/isolation/specs/vacuum-extending-freeze.spec
@@ -0,0 +1,124 @@
+# 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:
+# 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..e0e5561d1cb
--- /dev/null
+++ b/src/test/isolation2/expected/vacuum_analyze_stats.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.
+
+-- 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)
+-- 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;
+ALTER
+SELECT pg_reload_conf();
+ 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_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..4a08706a8e5
--- /dev/null
+++ b/src/test/isolation2/expected/vacuum_ao_stats.out
@@ -0,0 +1,173 @@
+-- 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
+--
+-- 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.
+--
+-- 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);
+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 = 1;
+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)
+
+-- Finish a successful vacuum after the failed distributed transaction.
+1: VACUUM vacstat_ao_row;
+VACUUM
+
+-- 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. 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
+-------------+-------------
+ 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: ...
+
+-- 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/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..2ffdacb52c1
--- /dev/null
+++ b/src/test/isolation2/sql/vacuum_analyze_stats.sql
@@ -0,0 +1,76 @@
+-- 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();
+-- 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
+ 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;
+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..d691a7983d9
--- /dev/null
+++ b/src/test/isolation2/sql/vacuum_ao_stats.sql
@@ -0,0 +1,108 @@
+-- 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
+--
+-- 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.
+--
+-- 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);
+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 = 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
+ 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;
+
+-- Finish a successful vacuum after the failed distributed transaction.
+1: VACUUM 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. 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()
+ 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:
+
+-- Restore the test cluster defaults.
+!\retcode gpconfig -r track_cost_delay_timing --skipvalidation;
+!\retcode gpconfig -r vacuum_cost_limit --skipvalidation;
+!\retcode gpstop -u;
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..2327f4d988f 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 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 82166f03ce0..bf73ee408c1 100644
--- a/src/test/modules/test_misc/meson.build
+++ b/src/test/modules/test_misc/meson.build
@@ -16,8 +16,12 @@ 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/021_vacuum_vm_pages.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..61848e9bfab
--- /dev/null
+++ b/src/test/modules/test_misc/t/016_index_vacuum_time.pl
@@ -0,0 +1,94 @@
+# 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,
+# 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..f6393cdfcac
--- /dev/null
+++ b/src/test/modules/test_misc/t/017_vacuum_failsafe.pl
@@ -0,0 +1,85 @@
+# 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
+# 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..a3b532bfc78
--- /dev/null
+++ b/src/test/modules/test_misc/t/018_vacuum_interrupts.pl
@@ -0,0 +1,152 @@
+# 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.
+#
+# 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 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'
+ AND wait_event = 'VacuumDelay'])
+ 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');
+
+# 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();
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..fff04b68e3e
--- /dev/null
+++ b/src/test/modules/test_misc/t/021_vacuum_vm_pages.pl
@@ -0,0 +1,62 @@
+# 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.
+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, pages_all_visible FROM pg_stat_all_tables
+WHERE relid = 'vm_pages'::regclass
+});
+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, 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{
+UPDATE vm_pages SET padding = 'changed';
+VACUUM (FREEZE) vm_pages;
+});
+is($node->safe_psql('postgres', qq{
+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 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 AND pages_all_visible = 0
+FROM pg_stat_all_tables WHERE relid = 'vm_pages'::regclass
+}), 't', 'relation statistics reset clears both work counters');
+$node->stop;
+done_testing();
diff --git a/src/test/regress/expected/rules.out b/src/test/regress/expected/rules.out
index 614ffea1784..625eec93cc6 100644
--- a/src/test/regress/expected/rules.out
+++ b/src/test/regress/expected/rules.out
@@ -1798,7 +1798,18 @@ 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_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 pg_index i ON ((c.oid = i.indrelid)))
LEFT JOIN pg_namespace n ON ((n.oid = c.relnamespace)))
@@ -1916,7 +1927,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 +2055,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 +2181,18 @@ 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,
+ pages_frozen,
+ pages_all_visible,
+ 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 +2240,35 @@ 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,
+ pages_frozen,
+ pages_all_visible,
+ 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..594dcdc1a96 100644
--- a/src/test/regress/expected/vacuum_stats.out
+++ b/src/test/regress/expected/vacuum_stats.out
@@ -28,4 +28,90 @@ AND relallvisible =
t
(1 row)
-DROP TABLE vacstat_test
+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 45a9b6466c4..9f5b35205c5 100644
--- a/src/test/regress/sql/vacuum_stats.sql
+++ b/src/test/regress/sql/vacuum_stats.sql
@@ -19,4 +19,52 @@ AND relallvisible =
(SELECT SUM(relallvisible) FROM gp_dist_random('pg_class')
WHERE oid='vacstat_test'::regclass);
-DROP TABLE vacstat_test
+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;