Registry Mirror
Skip to content

Conversation

@Alena0704

@Alena0704 Alena0704 commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Make VACUUM work available through native cumulative statistics for tables,
indexes and databases.

Collect tuple removal, remaining and missed dead tuples, scanned and removed
pages, and freeze-age-driven vacuums.
For append-optimized tables, collect segment counts, completed compactions,
moved tuples and remaining hidden rows.

Report index work as per-call deltas and correct SP-GiST accounting for
previously empty pages. Database totals exclude separate index reports to
avoid double counting.

Store dead_tuples and total_file_segs as last-run samples; other work counters
accumulate. Use ordinary statistics snapshots, resets, DROP handling and
clean-shutdown persistence.

Measurement, cumulative storage, and catalog functions/views are introduced
in separate commits.

Impact

Makes VACUUM work statistics available for heap, AO/AOCO tables and indexes
without an extension. Native cumulative counters are updated when
track_counts is enabled and exposed through local and cluster-wide views.

Adds counter maintenance during VACUUM and increases relation and database
statistics entry sizes. Bumps the catalog and cumulative-statistics file
versions; development clusters initialized with the previous catalog version
require initdb.

Type of Change

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

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_04_native_work branch 3 times, most recently from 4372a3f to d5ee92a Compare November 1, 2026 15:21
@Alena0704
Alena0704 marked this pull request as ready for review November 1, 2026 15:25
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 added a commit to Alena0704/cloudberry that referenced this pull request Nov 1, 2026
Merge the current apache#2106 branch, including the updates from apache#2102-apache#2105.
Read frozen/all-visible page counters through their native getters and
preserve them across work-only resets. Keep AO phase resource accounting
compatible with the resource-only hook and database-only index-insertion
aggregate. Advance the statistics file format for the combined layout.

Update reset tests, native-source comparisons, Meson test registration,
and the repeatable-read expectation for a relation without resources yet.
Document the native page-counter sources and reset semantics.

Validation: full assert-enabled macOS build, 11 extension TAP files
(202 tests), 14 core TAP files (210 tests), and the existing isolation
scenario via isolationtester with exact expected-output comparison.
Build diagnostic overrides cover pre-existing macOS warnings outside
this change. Distributed cluster regressions were not run.

Assisted-by: ChatGPT
@Alena0704
Alena0704 removed the request for review from chenjinbao1989 November 2, 2026 18:18
@Alena0704
Alena0704 force-pushed the vacuum_stats_04_native_work branch from 340f5ed to fdba8ac Compare November 5, 2026 09:12
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 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 added a commit to Alena0704/cloudberry that referenced this pull request Nov 5, 2026
Collect and expose buffer, WAL and I/O usage for heap and AO tables, indexes and databases. Add local and cluster views, independent collection controls and resets, clean-shutdown persistence and transactional cleanup for dropped objects. Build on the linearized prerequisites from PRs apache#2102 through apache#2105.
@Alena0704
Alena0704 force-pushed the vacuum_stats_04_native_work branch 2 times, most recently from 836647a to 6c93dca Compare November 10, 2026 09:01
@leborchuk

Copy link
Copy Markdown
Contributor

cloudberry-pr2105-ocr.txt

Found some issues by OCR, PTAL, looks that we could measure stats.pages_deleted more precisely

@Alena0704
Alena0704 force-pushed the vacuum_stats_04_native_work branch 3 times, most recently from bbd535d to 3f2bbbf Compare November 16, 2026 19:54
@Alena0704
Alena0704 force-pushed the vacuum_stats_04_native_work branch from 3f2bbbf to 86c8217 Compare November 17, 2026 14:48

@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 addressing the OCR findings. Three things should be fixed before merging: CI is red (1), AO compaction stats are published before the distributed transaction commits (2), and the PR conflicts with main (3). The rest is smaller. I built this PR (head 86c8217b893) and ran items 1 and 2 locally.

1. CI: ic-singlenode fails on all three platforms (main is green)

In packcore the server PANICs:

PANIC:  could not create file "pg_wal/xlogtemp.5508": No such file or directory

The tests after it then fail because the server restarted.

The bug is in packcore.sql, not in your code. Its plpython DO block runs os.chdir('/tmp') (line 76) inside the backend and never changes back. Each backend opens WAL segment files itself, by the relative path pg_wal/.... So once the working directory is /tmp, the first time that backend has to open a WAL segment, it PANICs. Whether that happens during packcore depends on the WAL position left by the earlier tests. This PR changes prevent_ao_wal, two tests earlier, and that is enough to move the position.

I reproduced it with a single-node demo cluster (NUM_PRIMARY_MIRROR_PAIRS=0, as in ic-singlenode), running singlenode_isolation2 up to packcore:

variant prevent_ao_wal packcore
this PR ok PANIC, same message (2 of 2 runs)
this PR, prevent_ao_wal.sql/.out taken from main fails (WAL record order, the reason you changed it) ok (2 of 2 runs)
this PR, packcore.sql changes back to the old directory ok no PANIC

The mechanism also shows directly. In one session, DO $$ import os; os.chdir('/tmp') $$ LANGUAGE plpython3u; followed by SELECT pg_switch_wal(); gives the same PANIC. With a chdir back at the end of the DO, it works.

Suggested fix: save os.getcwd() before os.chdir('/tmp'), and change back before each exit from the DO block (a try/finally is simplest). expected/packcore.out echoes the DO source, so it needs the same edit. The fix could go in this PR or in a small separate one.

2. AO compaction stats survive a rollback

src/backend/commands/vacuum_ao.c:492-515

After every AO phase, this code calls pgstat_report_vacuum_stats_phase(). That function adds the deltas straight into the shared relation entry and into the pending database entry. Neither write is undone on abort.

The compaction phase does not run in its own transaction. vacuum.c:656 sets use_own_xacts = false for VACOPT_AO_COMPACT_PHASE, and the QD dispatches it as a two-phase transaction. Suppose a segment finishes compaction, and then the distributed transaction aborts: a cancel, an error on another segment, or a failed PREPARE. That segment keeps compacted_segments, tuples_moved, tuples_deleted, pages_scanned and the database totals for work that was rolled back. The next VACUUM redoes the compaction and counts it again.

Reproduced on a 3-segment demo cluster. The setup is an AO table with 30000 rows, half of them deleted. vacuum_ao_after_compact is suspended on content 0, and the VACUUM is cancelled once the fault triggers. Values are compacted_segments / tuples_moved from gp_stat_vacuum_tables:

content 0 content 1 content 2
after the cancel 0 / 0 1 / 5076 1 / 4926
after one more, successful VACUUM 1 / 4998 2 / 10152 2 / 9852

After the cancel, __gp_aoseg still shows segno 1 with all its rows and state 1, so the compaction was rolled back. The successful VACUUM then moved 5076 and 4926 rows on contents 1 and 2. Those two contents report exactly twice that.

Repro
CREATE EXTENSION IF NOT EXISTS gp_inject_fault;
CREATE TABLE ao_abort(a int) WITH (appendonly=true) DISTRIBUTED BY (a);
INSERT INTO ao_abort SELECT generate_series(1,30000);
DELETE FROM ao_abort WHERE a % 2 = 0;
SELECT gp_stat_reset_vacuum_stats('ao_abort'::regclass);
SELECT gp_inject_fault('vacuum_ao_after_compact', 'suspend', dbid)
  FROM gp_segment_configuration WHERE content = 0 AND role = 'p';
-- session 2: VACUUM ao_abort;
SELECT gp_wait_until_triggered_fault('vacuum_ao_after_compact', 1, dbid)
  FROM gp_segment_configuration WHERE content = 0 AND role = 'p';
SELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE query = 'VACUUM ao_abort;';
SELECT gp_inject_fault('vacuum_ao_after_compact', 'reset', dbid)
  FROM gp_segment_configuration WHERE content = 0 AND role = 'p';
SELECT gp_segment_id, compacted_segments, tuples_moved
  FROM gp_stat_vacuum_tables WHERE relname = 'ao_abort' ORDER BY 1;
SELECT segment_id, segno, tupcount, state FROM gp_toolkit.__gp_aoseg('ao_abort') ORDER BY 1, 2;
VACUUM ao_abort;
SELECT gp_segment_id, compacted_segments, tuples_moved
  FROM gp_stat_vacuum_tables WHERE relname = 'ao_abort' ORDER BY 1;

This came in with the fix for OCR item 4 (QE replaced between phases). There is precedent: upstream ANALYZE also reports before commit (pgstat_report_analyze()). So I'd accept either of these:

  • publish the compaction-phase deltas only after the distributed commit, or
  • keep the current behaviour and document that these counters can include rolled-back work.

#2104 has the same OCR item unfixed (its pre-cleanup/compaction times are lost when the gang is replaced). It would be good if the two PRs used the same approach.

3. Conflict with main

git merge-tree against current main reports conflicts in src/include/catalog/catversion.h, src/include/pgstat.h and src/test/modules/test_misc/meson.build.

  • CATALOG_VERSION_NO 302610091 is now lower than main's 302610191.
  • PGSTAT_FILE_FORMAT_ID must be a value that is neither main's 0x01A5BCC0 nor the one #2104 ends up with. If it reuses main's value, a stats file written by a main build passes the ID check and gets read with the new entry layout.
  • #2104 bumps both constants too, so whichever PR lands second bumps again.
  • Main's pluggable stats kinds also changed the reset code in pgstat_shmem.c, which is where the new reset function lives. Please re-check that function after the rebase.

4. Replicated AO auxiliary relations are not divided by numsegments

src/backend/catalog/system_views_gp_summary.sql:567-570, and the index summary at :610-614

The divisor is looked up only for TOAST owners, through reltoastrelid. The aoseg, block-directory and visimap relations (relkind o/b/M) and their indexes have no gp_distribution_policy row, so their divisor is 1. Take a DISTRIBUTED REPLICATED AO table: the parent row is divided, but its auxiliary rows show numsegments × the work. This is the remaining part of OCR item 1. Resolving the owner through pg_appendonly (segrelid, blkdirrelid, visimaprelid and their index columns) would cover it.

Smaller things

  • src/backend/commands/vacuum.c:3898: index dead_pages adds pages_deleted - pages_free on every cleanup. That is the current number of deleted pages not yet recycled, but it is summed like a count of events. For a btree on an AO/AOCO table, BTPageIsRecyclable() (nbtree.h:300) never recycles a page, because it requires a heap table. So the counter grows by the same amount on every VACUUM; 024_ao_dead_pages.pl asserts 3× after three runs. If the column means "dead pages right now", overwrite it like dead_tuples instead of adding.
  • Bitmap indexes always report 0 tuples_deleted / pages_deleted, because bmbulkdelete() rebuilds the index and sets tuples_removed = 0 (bitmap.c:559). Worth a line in the docs.
  • gp_stat_vacuum_summary sums freeze_age_vacuum_count over the coordinator and the segments. The coordinator also runs heap_vacuum_rel() on its empty copy of a distributed table. From reading the code, one aggressive VACUUM therefore shows N+1 in the database summary and N in the table summary.
  • pg_stat_vacuum.stats_reset shows the database-wide reset time. The new pg_stat_reset_vacuum_stats() doesn't update it, so after a vacuum-only reset the column is misleading.
  • The 8 new TAP tests in src/test/modules/test_misc never run in CI. No job in build-cloudberry.yml runs that directory, and CI builds with autoconf, so the meson.build entries don't help either.
  • 86c8217b893 ("Add a native reset for VACUUM work counters") also carries the GIN, hash, AO-phase and view fixes, plus unrelated test changes (pg_rewind_fail_missing_xlog, prevent_ao_wal). Splitting it would make the history easier to review and bisect.

Assemble backend-local tuple and page measurements and take per-call
snapshots of the existing index results. Access methods accumulate
results
across passes, so retain each pass's delta without counting earlier work
again. Share the measurement helper between serial and parallel vacuum.

Keep SP-GiST's newly deleted page count cumulative within one vacuum,
without counting pages that were already empty on entry. Handle AMs that
reset their newly deleted page count between passes.

Adapt to PostgreSQL 16's existing recently_dead_tuples,
missed_dead_tuples,
pages_scanned, pages_removed and missed_dead_pages counters. Assemble
these
measurements independently of optional hooks; storage and SQL follow in
separate reporting commits.

Adapted-from: f2592a3
Introduce dead_pages in LVRelState and PgStat_VacuumStats. Count heap
pages
that retain recently dead tuples in both pruning and no-prune scans.
Keep this measurement distinct from pages with dead tuples missed
because
of buffer pins. For index cleanup, derive the count from deleted pages
that are not yet reusable.

Cumulative statistics storage and SQL exposure follow separately.

Adapted-from: 37a4753
Reuse the existing heap tuples_frozen measurement for native work
statistics.
Remember the result of vacuum_get_cutoffs before DISABLE_PAGE_SKIPPING
can
force aggressive mode. Include this classification in backend-local work
measurements, keeping freeze-age vacuums distinct from page-skipping
options and wraparound failsafe activation.

Cumulative statistics storage and SQL exposure follow separately.

Adapted-from: cefc6ba
Count completed compactions, moved tuples, scanned pages and the final
segment count without an extension hook. Discard state left over from an
interrupted operation. Keep per-index work measurements for each pass.
Native cumulative storage and SQL reporting follow separately.

Adapted-from: 6f38fb2
Connect the previously introduced heap, index and AO measurements to
ordinary relation and database statistics independently of any extension
hook. Include them in native snapshots, resets, transactional drops and
clean-shutdown persistence. Store dead_tuples and total_file_segs as
last-run samples; other work counters accumulate. Exclude index reports
and last-run samples from database totals.

Advance the statistics-file format for the stored fields. Catalog
functions, views and tests follow in a separate SQL reporting commit.
Publish cumulative tuple, page and AO compaction counters through native
SQL getters and local, per-segment and cluster summary views. Keep
last-run
snapshots separate from cumulative work and normalize replicated
relations.
Include heap/index/AO tests for counters, resets, snapshots and
persistence.
Count pending-list deletion and hash overflow release, and report retained
GIN pages across cleanup calls. Add targeted index work coverage.
Include AO auxiliary heap relations in native views. Resolve a TOAST
relation or index through its owning table for replicated summaries.
Preserve phase deltas when a different QE performs post-cleanup, while
retaining final table samples until the last phase completes.
Reset one relation or the current database without clearing other native
statistics or extension metrics. Add a privileged cluster wrapper and
cover scope, permissions, pending work, and restart behavior.
@Alena0704
Alena0704 force-pushed the vacuum_stats_04_native_work branch from 86c8217 to e54dd74 Compare November 26, 2026 14:32
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.

3 participants