pgsql: Fix double-free in pg_stat_autovacuum_scores.

From: Nathan Bossart <nathan(at)postgresql(dot)org>
To: pgsql-committers(at)lists(dot)postgresql(dot)org
Subject: pgsql: Fix double-free in pg_stat_autovacuum_scores.
Date: 2026-04-09 18:10:26
Message-ID: E1wAtph-000B3M-26@gemulon.postgresql.org
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-committers

Fix double-free in pg_stat_autovacuum_scores.

Presently, relation_needs_vacanalyze() unconditionally frees the
pgstat entry returned by pgstat_fetch_stat_tabentry_ext(). This
behavior was first added by commit 02502c1bca to avoid memory
leakage in autovacuum. While this is fine for autovacuum since it
forces stats_fetch_consistency to "none", it is not okay for other
callers that use "cache" or "snapshot". This manifests as a
double-free when pg_stat_autovacuum_scores is called multiple times
in the same transaction.

To fix, add a "bool *may_free" parameter to
pgstat_fetch_stat_tabentry_ext() that returns whether it is safe
for the caller to explicitly pfree() the result. If a caller would
rather leave it to the memory context machinery to free the result,
it can pass NULL as the "may_free" argument (or just ignore its
value).

Oversight in commit 87f61f0c82.

Reported-by: Tender Wang <tndrwang(at)gmail(dot)com>
Reported-by: Alexander Lakhin <exclusion(at)gmail(dot)com>
Suggested-by: Andres Freund <andres(at)anarazel(dot)de>
Suggested-by: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Author: Sami Imseih <samimseih(at)gmail(dot)com>
Discussion: https://postgr.es/m/CAHewXNkJKdwb3D5OnksrdOqzqUnXUEMpDam1TPW0vfUkW%3D7jUw%40mail.gmail.com
Discussion: https://postgr.es/m/5684f479-858e-4c5d-b8f5-bcf05de1f909%40gmail.com

Branch
------
master

Details
-------
https://git.postgresql.org/pg/commitdiff/71ff232a5bc40f36365be985da72b8b6fa275811

Modified Files
--------------
src/backend/postmaster/autovacuum.c | 7 +++++--
src/backend/utils/activity/pgstat.c | 18 +++++++++++++++++-
src/backend/utils/activity/pgstat_backend.c | 3 ++-
src/backend/utils/activity/pgstat_database.c | 2 +-
src/backend/utils/activity/pgstat_function.c | 2 +-
src/backend/utils/activity/pgstat_relation.c | 12 +++++++-----
src/backend/utils/activity/pgstat_replslot.c | 3 ++-
src/backend/utils/activity/pgstat_subscription.c | 2 +-
src/include/pgstat.h | 3 ++-
src/include/utils/pgstat_internal.h | 3 ++-
.../modules/test_custom_stats/test_custom_var_stats.c | 3 ++-
11 files changed, 42 insertions(+), 16 deletions(-)

Browse pgsql-committers by date

  From Date Subject
Next Message Masahiko Sawada 2026-04-09 19:12:56 Re: pgsql: Allow autovacuum to use parallel vacuum workers.
Previous Message Masahiko Sawada 2026-04-09 16:14:15 pgsql: Remove an unstable wait from parallel autovacuum regression test