From abc19158da02689c3c12082519bf85f11ab96feb Mon Sep 17 00:00:00 2001
From: Sami Imseih <samimseih@gmail.com>
Date: Wed, 8 Apr 2026 18:06:46 +0000
Subject: [PATCH v1 1/1] Fix double free in relation_needs_vacanalyze

When relation_needs_vacanalyze is executed multiple times with
stat_fetch_consistency other than NONE, a double free occurs
for the table stats. First in relation_needs_vacanalyze, then
when the snapshot's memory context is freed. In the NONE case,
the snapshot is stored in the caller's memory context, so it's
the caller's responsibility to free the memory.

Fix this by only calling pfree inside relation_needs_vacanalyze
when stat_fetch_consistency is NONE.
---
 src/backend/postmaster/autovacuum.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index bd626a16363..b1d12e3a61c 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -3327,7 +3327,13 @@ relation_needs_vacanalyze(Oid relid,
 			 anltuples, anlthresh, scores->anl,
 			 scores->xid, scores->mxid);
 
-	pfree(tabentry);
+	/*
+	 * In PGSTAT_FETCH_CONSISTENCY_NONE mode, stats are palloc'd in the
+	 * caller's memory context and must be freed explicitly.  In other modes,
+	 * they are managed by the snapshot's memory context.
+	 */
+	if (pgstat_fetch_consistency == PGSTAT_FETCH_CONSISTENCY_NONE)
+		pfree(tabentry);
 }
 
 /*
-- 
2.50.1

