Registry Mirror
Skip to content

Conversation

@Alena0704

Copy link
Copy Markdown
Collaborator

What does this PR do?

Expose maintenance duration and visibility-map stability through native
cumulative statistics and catalog views.

  • Track VACUUM and ANALYZE elapsed time, index vacuum time, and database
    vacuum totals.
  • Measure cost-based delays when track_cost_delay_timing is enabled and
    expose delay time in progress reporting.
  • Count completed vacuums that entered failsafe mode and vacuums interrupted
    by errors.
  • Track cleared all-visible and all-frozen VM bits.
  • Add pg_class.relallfrozen and maintain it through vacuum, analyze and
    relation lifecycle operations.
  • Measure active AO vacuum phases, excluding gaps between phases.

Expose the statistics through SQL getters and local, per-instance and cluster
summary views. Catalog exposure and tests are kept in a separate commit.

Test Plan

  • Added SQL and isolation coverage for VM and AO behavior.

Impact

Changes the pg_class layout and bumps the catalog version; development
clusters require initdb. Updates the cumulative-statistics file format.

Type of Change

  • Bug fix (non-breaking change)
  • New feature (non-breaking change)
  • Breaking change (fix or feature with breaking changes)
  • Documentation update

Breaking Changes

Test Plan

  • Unit tests added/updated
  • Integration tests added/updated
  • Passed make installcheck
  • Passed make -C src/test installcheck-cbdb-parallel

Checklist

@Alena0704
Alena0704 force-pushed the vacuum_stats_03_native_timing_vm branch 2 times, most recently from 2a67beb to ebd5f98 Compare November 1, 2026 14:59
@Alena0704
Alena0704 marked this pull request as ready for review November 1, 2026 15:01
Alena0704 added a commit to Alena0704/cloudberry that referenced this pull request Nov 1, 2026
Merge the current heads of apache#2102, apache#2103, apache#2104 and apache#2105. Keep resource
hooks independent of native completion reports, adopt the new VM counter
layout, and remove the superseded relallfrozen catalog changes.

Account for AO compaction index insertions in the database resource
aggregate without attributing the all-index sample to one relation.
Preserve native timing, work and interruption accounting exactly once.
Update catalog/statistics format versions, regression expectations and
Meson TAP registration. Cover AO/AOCO resource aggregation and preservation
of native page counters across work-only resets.

Validation: full assert-enabled macOS build; 14 core TAP files (210 tests),
5 existing extension TAP files (81 tests), and AO/AOCO resource TAP
coverage (14 tests). macOS build uses diagnostic overrides for pre-existing
warnings outside these changes. Distributed cluster regressions not run.

Assisted-by: ChatGPT
@Alena0704
Alena0704 removed the request for review from chenjinbao1989 November 2, 2026 18:18
Alena0704 added a commit to Alena0704/cloudberry that referenced this pull request Nov 5, 2026
Integrate PRs apache#2102, apache#2103, apache#2104 and apache#2105 on current main.
Preserve the existing extension integration and the vacuum_stats
expected-output whitespace fix.
@Alena0704
Alena0704 force-pushed the vacuum_stats_03_native_timing_vm branch from 10064ad to 87deb7a Compare November 5, 2026 09:27
Alena0704 added a commit to Alena0704/cloudberry that referenced this pull request Nov 5, 2026
Integrate PRs apache#2102, apache#2103, apache#2104 and apache#2105 on current main.
Preserve the existing extension integration and the vacuum_stats
expected-output whitespace fix.
@leborchuk

Copy link
Copy Markdown
Contributor

cloudberry-pr2104-ocr.txt

See issues found by OCR. PTAL, allocation in a critical section looks serious and should be fixed

@Alena0704
Alena0704 force-pushed the vacuum_stats_03_native_timing_vm branch 2 times, most recently from 88606f5 to 76ed992 Compare November 10, 2026 11:00
@Alena0704

Copy link
Copy Markdown
Collaborator Author

cloudberry-pr2104-ocr.txt

See issues found by OCR. PTAL, allocation in a critical section looks serious and should be fixed

Thank you for your review. Fixed.

@Alena0704
Alena0704 force-pushed the vacuum_stats_03_native_timing_vm branch from 76ed992 to 5a561d6 Compare November 16, 2026 19:10

@leborchuk leborchuk left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks

@Alena0704
Alena0704 force-pushed the vacuum_stats_03_native_timing_vm branch from 5a561d6 to b55b91e Compare November 16, 2026 21:12
@Alena0704
Alena0704 force-pushed the vacuum_stats_03_native_timing_vm branch from b55b91e to c8f1507 Compare November 17, 2026 14:37

@MisterRaindrop MisterRaindrop left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the work on this. Two things should be fixed before merging: the analyze-time columns in gp_stat_all_tables_summary (1), and the conflict with main, where PGSTAT_FILE_FORMAT_ID needs a new value (2). The rest is smaller. I built this PR (head a47c2399dd7) and ran item 1 on a 3-segment demo cluster.

1. gp_stat_all_tables_summary reports auto-analyze time as manual analyze time

src/backend/catalog/system_views_gp_summary.sql:143-144 (computed at :182-183)

The two time columns are summed over the segments (m). The two count columns come from the coordinator (s). ANALYZE also runs do_analyze_rel() on every segment, and pgstat_report_analyze() there decides manual vs auto with IsAutoVacuumWorkerProcess(). A QE is never an autovacuum worker. So the segments record every ANALYZE as manual, even one that the coordinator's autovacuum started.

After one auto-analyze of a user table:

analyze_count autoanalyze_count total_analyze_time total_autoanalyze_time
gp_stat_all_tables_summary 0 1 16 0
coordinator 0 1 0 21
each segment 1 0 5-6 0

So for user tables total_autoanalyze_time stays 0, and auto-analyze work shows up as manual time. Taking both time columns from s makes them agree with the counts. The coordinator's time covers the whole ANALYZE, including the part that runs on the segments. For a manual ANALYZE the two sources happen to be close: 32 ms summed over the segments vs 33 ms on the coordinator in my run.

Repro
-- coordinator only: gpconfig -c autovacuum_naptime -v 2 --masteronly && gpstop -u
CREATE TABLE autoana_t (a int)
  WITH (autovacuum_analyze_threshold = 100, autovacuum_analyze_scale_factor = 0)
  DISTRIBUTED BY (a);
INSERT INTO autoana_t SELECT generate_series(1, 200000);
-- wait until pg_stat_all_tables.autoanalyze_count = 1 on the coordinator
SELECT analyze_count, autoanalyze_count, total_analyze_time, total_autoanalyze_time
  FROM gp_stat_all_tables_summary WHERE relname = 'autoana_t';
SELECT gp_segment_id, analyze_count, autoanalyze_count, total_analyze_time, total_autoanalyze_time
  FROM gp_stat_all_tables WHERE relname = 'autoana_t' ORDER BY 1;

No test covers these two columns yet, so a test along these lines would help.

2. Conflict with main; PGSTAT_FILE_FORMAT_ID needs a fresh value

src/include/pgstat.h:249

Main has since merged the pluggable cumulative statistics backport. The PR now conflicts in src/include/pgstat.h and src/test/modules/test_misc/meson.build. Main's format ID is now 0x01A5BCC0; this PR uses 0x01A5BCB6.

When resolving, please don't keep main's value. If you do, a stats file written by a main build passes the ID check, and it gets read with this PR's new PgStat_StatTabEntry / PgStat_StatDBEntry layout. The file should be discarded instead. Any unused value works, for example 0x01A5BCC1.

#2105 bumps the same constant and catversion. Whichever of the two lands second has to bump both again.

3. The OCR item "allocation in a critical section" is unchanged in the code

src/include/pgstat.h:776-789, called from src/backend/access/heap/visibilitymap.c:206-208

The reply on Nov 16 says this is fixed, but both macros still call pgstat_should_count_relation(). When rel->pgstat_info is NULL, that function calls pgstat_assoc_relation() → pgstat_prep_pending_entry(), which allocates memory. The heapam callers run visibilitymap_clear_rel() inside START_CRIT_SECTION().

I don't think it can happen today. Every heapam caller reads the same heap page through ReadBufferExtended() first, and the pgstat_count_buffer_read() there sets pgstat_info outside the critical section. But nothing in the VM code states or checks that assumption. Suggest counting only when the entry already exists, e.g. if ((rel)->pgstat_info != NULL) in the two macros. The cost is that a clear can go uncounted in a case that doesn't occur today. At minimum, an Assert would document the assumption.

4. The other two OCR items also look unchanged

  • OCR 2: pre-cleanup and compaction times are kept in a backend-local static and published by the worker that runs post-cleanup. If the QE gang is replaced between phases, those times are lost, but vacuum_count still increments.
  • OCR 3: track_cost_delay_timing is still in unsync_guc_name.h.

If both are intentional, one sentence in the PR saying so would help. #2105 solves the OCR 2 problem for its own counters by publishing after every phase. That creates a different problem: the compaction phase runs inside the dispatched two-phase transaction, so the published numbers survive a rollback (details in my review of #2105). It would be good if the two PRs handled this the same way.

5. PR description

The description still lists pg_class.relallfrozen. That column is no longer in the code; pages_frozen / pages_all_visible replaced it.

Smaller things

  • src/backend/access/heap/vacuumlazy.c:1543: VM_ALL_VISIBLE() now runs inside START_CRIT_SECTION() on the empty-page path. It is safe today because lazy_scan_heap() has already pinned the right VM page, so visibilitymap_get_status() does no I/O. Moving the check above START_CRIT_SECTION() removes that dependency at no cost.
  • src/backend/commands/vacuum.c:2904: the error counter only wraps table_relation_vacuum(). A failed heap VACUUM FULL goes through cluster_rel() a few lines up and is not counted. Errors in vacuum_open_relation() are not counted either. Please document what vacuum_interrupt_count covers.
  • gp_stat_vacuum_summary (system_views_gp_summary.sql:104-105) uses max() for vacuum_failsafe_count and vacuum_interrupt_count. Suppose segment 0 enters failsafe in one VACUUM and segment 1 in the next: the summary shows 1. sum() counts segment-level events, which is at least well defined. Otherwise, please document what the value means.
  • The progress summary views (gp_stat_progress_vacuum_summary, gp_stat_progress_analyze_summary) don't expose the new delay_time column.
  • parallel_vacuum_worker_delay_ns (vacuum.c:122, :3260) is written but never read, and parallel vacuum is #if 0'd in vacuumlazy.c in this tree. The parallel timing code can go.
  • The new TAP tests t/016, t/017, t/018 and t/020 never run in CI. No job in build-cloudberry.yml runs src/test/modules/test_misc. CI builds with autoconf, so the meson.build entries don't run them either. Either add test_misc to the ic-tap list, or move the important assertions into regress/isolation2.
  • CI on the current head (merge commit a47c2399dd7) was cancelled. The last complete run, on c8f15070a82, was green. Please rerun it after the rebase.

@MisterRaindrop MisterRaindrop mentioned this pull request Nov 24, 2026
4 of 13 tasks
@Alena0704
Alena0704 force-pushed the vacuum_stats_03_native_timing_vm branch 2 times, most recently from 8454e97 to b3fb548 Compare November 26, 2026 10:53
@Alena0704

Copy link
Copy Markdown
Collaborator Author

Thanks for the work on this. Two things should be fixed before merging: the analyze-time columns in gp_stat_all_tables_summary (1), and the conflict with main, where PGSTAT_FILE_FORMAT_ID needs a new value (2). The rest is smaller. I built this PR (head a47c2399dd7) and ran item 1 on a 3-segment demo cluster.

1. gp_stat_all_tables_summary reports auto-analyze time as manual analyze time

src/backend/catalog/system_views_gp_summary.sql:143-144 (computed at :182-183)

The two time columns are summed over the segments (m). The two count columns come from the coordinator (s). ANALYZE also runs do_analyze_rel() on every segment, and pgstat_report_analyze() there decides manual vs auto with IsAutoVacuumWorkerProcess(). A QE is never an autovacuum worker. So the segments record every ANALYZE as manual, even one that the coordinator's autovacuum started.

After one auto-analyze of a user table:

analyze_count autoanalyze_count total_analyze_time total_autoanalyze_time
gp_stat_all_tables_summary 0 1 16 0
coordinator 0 1 0 21
each segment 1 0 5-6 0
So for user tables total_autoanalyze_time stays 0, and auto-analyze work shows up as manual time. Taking both time columns from s makes them agree with the counts. The coordinator's time covers the whole ANALYZE, including the part that runs on the segments. For a manual ANALYZE the two sources happen to be close: 32 ms summed over the segments vs 33 ms on the coordinator in my run.

Repro
No test covers these two columns yet, so a test along these lines would help.

2. Conflict with main; PGSTAT_FILE_FORMAT_ID needs a fresh value

src/include/pgstat.h:249

Main has since merged the pluggable cumulative statistics backport. The PR now conflicts in src/include/pgstat.h and src/test/modules/test_misc/meson.build. Main's format ID is now 0x01A5BCC0; this PR uses 0x01A5BCB6.

When resolving, please don't keep main's value. If you do, a stats file written by a main build passes the ID check, and it gets read with this PR's new PgStat_StatTabEntry / PgStat_StatDBEntry layout. The file should be discarded instead. Any unused value works, for example 0x01A5BCC1.

#2105 bumps the same constant and catversion. Whichever of the two lands second has to bump both again.

3. The OCR item "allocation in a critical section" is unchanged in the code

src/include/pgstat.h:776-789, called from src/backend/access/heap/visibilitymap.c:206-208

The reply on Nov 16 says this is fixed, but both macros still call pgstat_should_count_relation(). When rel->pgstat_info is NULL, that function calls pgstat_assoc_relation() → pgstat_prep_pending_entry(), which allocates memory. The heapam callers run visibilitymap_clear_rel() inside START_CRIT_SECTION().

I don't think it can happen today. Every heapam caller reads the same heap page through ReadBufferExtended() first, and the pgstat_count_buffer_read() there sets pgstat_info outside the critical section. But nothing in the VM code states or checks that assumption. Suggest counting only when the entry already exists, e.g. if ((rel)->pgstat_info != NULL) in the two macros. The cost is that a clear can go uncounted in a case that doesn't occur today. At minimum, an Assert would document the assumption.

4. The other two OCR items also look unchanged

  • OCR 2: pre-cleanup and compaction times are kept in a backend-local static and published by the worker that runs post-cleanup. If the QE gang is replaced between phases, those times are lost, but vacuum_count still increments.
  • OCR 3: track_cost_delay_timing is still in unsync_guc_name.h.

If both are intentional, one sentence in the PR saying so would help. #2105 solves the OCR 2 problem for its own counters by publishing after every phase. That creates a different problem: the compaction phase runs inside the dispatched two-phase transaction, so the published numbers survive a rollback (details in my review of #2105). It would be good if the two PRs handled this the same way.

5. PR description

The description still lists pg_class.relallfrozen. That column is no longer in the code; pages_frozen / pages_all_visible replaced it.

Smaller things

  • src/backend/access/heap/vacuumlazy.c:1543: VM_ALL_VISIBLE() now runs inside START_CRIT_SECTION() on the empty-page path. It is safe today because lazy_scan_heap() has already pinned the right VM page, so visibilitymap_get_status() does no I/O. Moving the check above START_CRIT_SECTION() removes that dependency at no cost.
  • src/backend/commands/vacuum.c:2904: the error counter only wraps table_relation_vacuum(). A failed heap VACUUM FULL goes through cluster_rel() a few lines up and is not counted. Errors in vacuum_open_relation() are not counted either. Please document what vacuum_interrupt_count covers.
  • gp_stat_vacuum_summary (system_views_gp_summary.sql:104-105) uses max() for vacuum_failsafe_count and vacuum_interrupt_count. Suppose segment 0 enters failsafe in one VACUUM and segment 1 in the next: the summary shows 1. sum() counts segment-level events, which is at least well defined. Otherwise, please document what the value means.
  • The progress summary views (gp_stat_progress_vacuum_summary, gp_stat_progress_analyze_summary) don't expose the new delay_time column.
  • parallel_vacuum_worker_delay_ns (vacuum.c:122, :3260) is written but never read, and parallel vacuum is #if 0'd in vacuumlazy.c in this tree. The parallel timing code can go.
  • The new TAP tests t/016, t/017, t/018 and t/020 never run in CI. No job in build-cloudberry.yml runs src/test/modules/test_misc. CI builds with autoconf, so the meson.build entries don't run them either. Either add test_misc to the ic-tap list, or move the important assertions into regress/isolation2.
  • CI on the current head (merge commit a47c2399dd7) was cancelled. The last complete run, on c8f15070a82, was green. Please rerun it after the rebase.

Thanks for the detailed review! Fixed the ANALYZE summary, VM accounting, and progress summaries, and updated the format IDs. AO timing is now published after each successful phase and survives a later rollback; completion is counted only after post-cleanup. track_cost_delay_timing remains instance-local, with this behavior documented. Added tests and wired them into CI. The fixes are folded into the PR commits, and conflicts with current main are resolved.

@MisterRaindrop MisterRaindrop left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@Alena0704
Alena0704 enabled auto-merge (rebase) November 26, 2026 14:28
michaelpq and others added 19 commits November 26, 2026 17:29
…alyze

This commit adds four fields to the statistics of relations, aggregating
the amount of time spent for each operation on a relation:
- total_vacuum_time, for manual vacuum.
- total_autovacuum_time, for vacuum done by the autovacuum daemon.
- total_analyze_time, for manual analyze.
- total_autoanalyze_time, for analyze done by the autovacuum daemon.

This gives users the option to derive the average time spent for these
operations with the help of the related "count" fields.

Bump PGSTAT_FILE_FORMAT_ID for the additions in PgStat_StatTabEntry.
Catalog functions, views and their version bump follow separately.

Author: Sami Imseih
Reviewed-by: Bertrand Drouvot, Michael Paquier
Discussion: https://postgr.es/m/CAA5RZ0uVOGBYmPEeGF2d1B_67tgNjKx_bKDuL+oUftuoz+=Y1g@mail.gmail.com

(cherry picked from commit 30a6ed0)

Cloudberry adaptation: time AO vacuum from its first phase and pass the
start timestamp to the collector at final cleanup, so the changed API is
usable by heap and AO immediately.

Co-authored-by: Alena Rybakina <alenka.rybakina@gmail.com>
This function is used in both vacuum and analyze code paths, and a
follow-up commit will require distinguishing between the two.  This
commit forces callers to specify whether they are in a vacuum or
analyze path, but it does not use that information for anything
yet.

Author: Nathan Bossart <nathandbossart@gmail.com>
Co-authored-by: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Discussion: https://postgr.es/m/ZmaXmWDL829fzAVX%40ip-10-97-1-34.eu-west-3.compute.internal

Backported from PostgreSQL 18 (commit e5b0b0c)
as a prerequisite of the vacuum statistics series.  Cloudberry adaptation:
the append-optimized and AOCS sample-row acquisition and compaction call
vacuum_delay_point() too; the former pass is_analyze = true, the latter
false.
This commit adds the amount of time spent sleeping due to
cost-based delay to the pg_stat_progress_vacuum and
pg_stat_progress_analyze system views.  A new configuration
parameter named track_cost_delay_timing, which is off by default,
controls whether this information is gathered. SQL view definitions and
the catalog version change are included in the native SQL reporting commit.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Co-authored-by: Nathan Bossart <nathandbossart@gmail.com>
Reviewed-by: Sami Imseih <samimseih@gmail.com>
Reviewed-by: Robert Haas <robertmhaas@gmail.com>
Reviewed-by: Masahiko Sawada <sawada.mshk@gmail.com>
Reviewed-by: Masahiro Ikeda <ikedamsh@oss.nttdata.com>
Reviewed-by: Dilip Kumar <dilipbalaut@gmail.com>
Reviewed-by: Sergei Kornilov <sk@zsrv.org>
Discussion: https://postgr.es/m/ZmaXmWDL829fzAVX%40ip-10-97-1-34.eu-west-3.compute.internal

Backported from PostgreSQL 18 (commit bb8dff9)
as a prerequisite of the vacuum statistics series.  Cloudberry adaptation:
the vacuum progress parameters of this branch end at num_dead_tuples, so
the delay time is PROGRESS_VACUUM_DELAY_TIME 7 (param8 of the view).
Cloudberry does not run parallel vacuum (see dead_items_alloc()),
so omit the unused parallel-worker delay accumulator. Local progress
reporting measures the VACUUM or ANALYZE backend's own cost delays.
The new GUC is listed in unsync_guc_names_array, next to track_io_timing,
as every GUC has to be in one of the two lists here.

SQL progress-view changes are separated into the native SQL reporting
commit; measurement, the GUC and progress counters are introduced here.
Port the process-local VacuumDelayTime accumulator from the REL_2_STABLE
commit. Accumulate measured cost-based VACUUM sleep time only while
track_cost_delay_timing is enabled, excluding ANALYZE. Consumers take
before/after differences to attribute delays to their own operations.

The preceding PostgreSQL 18 progress-view backport already provides the
GUC, its documentation, sample setting, unsynchronized registration and
sleep timing. Reuse that measurement and preserve both VACUUM and ANALYZE
progress reporting. Keep the accumulator in milliseconds as double to
match this branch's cumulative timing consumers, rather than the source
branch's int64 microseconds.

Extract the accumulator from the index/database timing commit and fold
in the ANALYZE exclusion previously included in the combined heap/index/AO
measurements commit. The final branch contents are unchanged.

Author: Bertrand Drouvot <bertranddrouvot.pg@gmail.com>
Discussion: https://postgr.es/m/ZmaXmWDL829fzAVX%40ip-10-97-1-34.eu-west-3.compute.internal
Backported from PostgreSQL 18 (commit bb8dff9).
(cherry picked from commit 01aaacb)

Co-authored-by: Nathan Bossart <nathandbossart@gmail.com>
Co-authored-by: Alena Rybakina <alenka.rybakina@gmail.com>
Accumulate elapsed time and cost-based delays over active AO vacuum phases,
excluding the gaps between phases. Discard state left over from an
interrupted operation. Prepare per-index timing measurements for the
subsequent cumulative-reporting change.

Adapted-from: 6f38fb2
Record index-pass elapsed and cost-delay time, including parallel workers
with the leader's autovacuum classification. Add cumulative table delay
time and database totals without adding index time to database totals a
second time. Include removed tuple counts in verbose index reports.

Catalog getters, views, documentation and SQL-dependent tests follow in
the separate native SQL reporting commit.
Accumulate relation and database failsafe counts for completed heap
vacuums. Pass false for AO, which has no heap wraparound failsafe mode.
Keep this counter distinct from scans made aggressive by the freeze age.

Catalog getters, views and tests follow in the native SQL reporting commit.
Count ERROR reports in the heap vacuum callback using local counters for database-local and shared relations. Transfer them to pending database statistics at transaction end. Test cancellation of a running vacuum.
Add visible_page_marks_cleared and frozen_page_marks_cleared counters to
pg_stat_all_tables tracking the number of times the all-visible and
all-frozen bits are cleared in the visibility map. These bits are cleared by
backend processes during regular DML operations. Hence, the counters are placed
in table statistic entry.

A high visible_page_marks_cleared rate relative to DML volume indicates
that modifications are scattered across previously-clean pages rather
than concentrated on already-dirty ones, causing index-only scans to
fall back to heap fetches.  A high frozen_page_marks_cleared rate indicates
that vacuum's freezing work is being frequently undone by concurrent
DML.

Authors: Alena Rybakina <lena.ribackina@yandex.ru>,
         Andrei Lepikhov <lepihov@gmail.com>,
         Andrei Zubkov <a.zubkov@postgrespro.ru>
Reviewed-by: Dilip Kumar <dilipbalaut@gmail.com>,
         Masahiko Sawada <sawada.mshk@gmail.com>,
         Ilia Evdokimov <ilya.evdokimov@tantorlabs.com>,
         Jian He <jian.universality@gmail.com>,
         Kirill Reshke <reshkekirill@gmail.com>,
         Alexander Korotkov <aekorotkov@gmail.com>,
         Jim Nasby <jnasby@upgrade.com>,
         Sami Imseih <samimseih@gmail.com>,
         Karina Litskevich <litskevichkarina@gmail.com>,
         Andrey Borodin <x4mmm@yandex-team.ru>

Backported-from: https://www.postgresql.org/message-id/attachment/205562/v45-0009-Track-table-VM-stability.patch

Co-authored-by: Andrei Lepikhov <lepihov@gmail.com>
Co-authored-by: Andrei Zubkov <zubkov@moonset.ru>
Connect AO index-pass timing measurements to cumulative statistics and
report interrupted vacuums. Add cumulative delay reporting for AO tables.
Failsafe and visibility-map counters remain inapplicable to AO.

The cluster isolation test is included later with its gp_stat_vacuum
dependency. Active-phase elapsed reporting is connected in a later commit.
Describe track_cost_delay_timing alongside the instrumentation it enables.
Give the accumulated instrumentation fields their own statistics-file format
identifier independent of the pluggable-statistics series.
Publish elapsed and cost-delay time after each successful AO phase,
preserving work if the next phase runs in a replacement QE. Exclude
gaps between phases and retain consumed time after a later rollback.
Only post-cleanup updates tuple estimates and the completed-vacuum
count. Remove obsolete cross-phase timing state.

SQL exposure, documentation and tests follow separately.
Add native SQL getters and local/cluster views for maintenance elapsed
and cost-delay time, failsafe runs, interrupted vacuums and cleared VM
bits. Use coordinator ANALYZE times alongside coordinator counts, sum
instance-level events, and expose worker delays in progress summaries.

Document per-phase AO timing and add isolation coverage for auto-analyze,
phase rollback, QE replacement and progress delays. Run the native
maintenance TAP tests in the ic-tap CI job.
Move cluster timing, index-summary cardinality, and
track_cost_delay_timing scope checks from the extension regression into
the core vacuum_stats test. Cover distributed and replicated tables, and
explicitly flush database statistics before checking their timing aggregate.
Reuse PostgreSQL 16 frozen_pages measurements for completed heap vacuums.
Expose pages_frozen through native statistics and summary views, with
documentation and reset/no-double-count coverage.
Count newly set all-visible VM marks while holding the heap page lock,
including empty-page and second-pass cleanup paths.
Expose pages_all_visible in native statistics, summary views and
VERBOSE output, and extend regression coverage.
Count at the table access method error boundary instead of
error-context callbacks, so caught expression-index exceptions
during AO compaction do not inflate vacuum_interrupt_count.
Preserve heap diagnostic context and rethrow escaping errors.

Wait for VacuumDelay before cancellation and cover caught and
escaping index exceptions for both AO storage orientations.
@Alena0704
Alena0704 force-pushed the vacuum_stats_03_native_timing_vm branch from b3fb548 to 23ed5dc Compare November 26, 2026 14:29
@tuhaihe

tuhaihe commented Nov 26, 2026 •

Copy link
Copy Markdown
Member

🤖 This is an automated review by Claude Code (OCR delegate mode), for reference only. It does not replace a review by a committer. Please check each point against the code before acting on it.

Details

Summary

Reviewed range: aeaa7ad0be..23ed5dc0d6b (19 commits, 67 files, +2920/−112).
Coverage: 51 of 51 reviewable files reviewed (16 .sgml/.dat/.out/.spec/.in/meson.build files were excluded by the tool. pg_proc.dat was checked separately and duplicate_oids reports no duplicate OIDs).

No blocking correctness bugs found. Several things look right:

  • QD dispatch happens after the local timer stops, so QD timing does not include segment wall time.
  • pgstat_count_vacuum_error() only bumps a static counter in PG_CATCH and folds it into pending stats in AtEOXact_PgStat_Database(), which is safe.
  • The VM-clear counters only increment pgstat_info fields, so they are safe inside critical sections.
  • The gp_stat_all_indexes_summary join fix (AND m.indexrelid = s.indexrelid) is a real bug fix.

The points below are mostly about the PR description, MPP semantics, and test stability.

Medium

1. The PR description says pg_class.relallfrozen is added, but the code does not add it

The description says "Add pg_class.relallfrozen and maintain it through vacuum, analyze and relation lifecycle operations" and "Changes the pg_class layout". The diff does not touch pg_class.h. t/021_vacuum_vm_pages.pl even asserts the column does not exist:

SELECT NOT EXISTS (SELECT FROM pg_attribute
                   WHERE attrelid = 'pg_class'::regclass AND attname = 'relallfrozen')
  • Please update the description (and the Impact section) to match the code.
  • Please drop that assertion. PostgreSQL 18 adds pg_class.relallfrozen upstream, so this test will fail on a future PG18 merge for no functional reason.

2. vacuum_interrupt_count counts one failed distributed VACUUM once per QE

pgstat_count_vacuum_error() runs in the PG_CATCH around table_relation_vacuum() on each instance. When one QE fails (for example during AO compaction), the other QEs get cancelled while still inside table_relation_vacuum(), so each of them also counts an interruption. The QD does not count it, because the QE error reaches the QD through dispatchVacuum(), outside the PG_TRY. As a result, gp_stat_vacuum_summary.vacuum_interrupt_count can report up to numsegments interruptions for one failed user command. (The comment in vacuum_ao_phase_timing.sql already notes that peers can be cancelled mid-phase.)

If that is intended (a per-instance count of interrupted local vacuums), please say so in monitoring.sgml for pg_stat_vacuum / gp_stat_vacuum_summary. Otherwise, consider counting on the QD for dispatched vacuums, or skipping errors that are cancellations caused by the QD.

3. Timing-dependent waits in isolation2/sql/vacuum_ao_stats.sql

  • SELECT pg_sleep(5); and SELECT pg_sleep(2); wait a fixed time for stats to flush. This is slow, and on a loaded CI runner it may not be long enough. The regress test already uses gp_stat_force_next_flush(). A flush on every segment (or a polling loop like wait_for_analyze_times() in vacuum_analyze_stats.sql) would be deterministic.
  • sum(total_vacuum_time) < 3000 is an absolute wall-clock upper bound summed over all segments. It can fail on slow or overloaded machines. A looser bound, or a relative check (for example compared with the elapsed time of the VACUUM statement), would be more robust.

Low / nits

  • vacuum_failsafe_count in gp_stat_all_tables_summary is summed without dividing by numsegments for replicated tables. Every other new column in that view (pages_frozen, pages_all_visible, *_page_marks_cleared, all times) is normalized. Either normalize it or add a comment explaining why it stays a raw sum.
  • Rounding is not consistent. Heap and index passes use TimestampDifferenceMilliseconds(), which rounds up and caps at INT_MAX ms. AO phases use rint(INSTR_TIME_GET_MILLISEC()). Each index pass therefore adds at least 1 ms, which inflates pg_stat_all_indexes.total_vacuum_time for tables with many short index passes. This is minor, but using instr_time with rint() everywhere would be more uniform.
  • contrib/pg_surgery/heap_surgery.c:267 still calls visibilitymap_clear() while it holds a real open relation, so VM clears from heap_force_kill/heap_force_freeze are not counted in visible/frozen_page_marks_cleared. Consider switching it to visibilitymap_clear_rel().
  • ginInsertCleanup() signature change. Upstream PG18 (e5b0b0c) kept the signature and passes false inside. Adding an is_analyze parameter changes an exported function, which affects out-of-tree GIN users and will cause conflicts on future cherry-picks. If the analyze attribution is needed, consider a static wrapper or a separate entry point, and note the deviation in the commit message.
  • isolation2/sql/vacuum_analyze_stats.sql turns on cluster-wide autovacuum/autovacuum_naptime with ALTER SYSTEM. If the test fails before the reset (for example the RAISE EXCEPTION timeout path), the settings stay on for the rest of the schedule. Consider moving the reset into a -- teardown-style step, or documenting the risk.
  • vacuumparallel.c. The commit message says Cloudberry does not run parallel vacuum, but the timing code is added to parallel_vacuum_process_one_index() anyway. Keeping it for upstream parity is fine. A one-line comment saying it is currently unreachable in Cloudberry would help readers.

Files reviewed

Area Files Status
Core vacuum/analyze vacuum.c, vacuum_ao.c, vacuumlazy.c, visibilitymap.c, heapam.c, analyze.c, vacuumparallel.c reviewed
Stats pgstat_relation.c, pgstat_database.c, pgstatfuncs.c, pgstat.h reviewed
Catalog / views system_views.sql, system_views_gp_summary.sql, pg_proc.dat (OID check only) reviewed
AM call sites gin/gist/hash/nbtree/spgist/bloom/file_fdw/AO/AOCS/typanalyze reviewed (mechanical vacuum_delay_point(bool) changes)
GUC / headers guc_tables.c, unsync_guc_name.h, progress.h, vacuum.h, gin_private.h, appendonly_compaction.h, visibilitymap.h, catversion.h reviewed
Tests isolation2 SQL (6), TAP 016/017/018/021, regress/sql/vacuum_stats.sql, schedules, test_misc/Makefile, CI workflow reviewed

Generated by Claude Code using ocr delegate (rules from OpenCodeReview, review performed by the agent). Findings are suggestions only.

@Alena0704
Alena0704 disabled auto-merge November 26, 2026 15:34
Count visibility-map clears by heap_force_kill and cover repeated surgery
on the same frozen page. Preserve the upstream ginInsertCleanup signature
with a separate auto-analyze entry point so cleanup delays retain their
ANALYZE attribution without changing existing GIN callers.

Use instr_time and nearest-millisecond rounding for maintenance timing,
including serial and parallel index passes. Remove the INT_MAX duration
cap and avoid rounding every short index pass up to one millisecond.
Clarify per-instance interrupt and failsafe counts in cluster summaries.

Replace fixed AO statistics waits with a forced cluster flush, remove the
obsolete wall-clock bound and relallfrozen absence assertion, and restore
auto-analyze settings immediately after the test wait.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants