From 961f28a1aeeba1c1ab8a2c63277405c97e7f820d Mon Sep 17 00:00:00 2001
From: Michael Banck <michael.banck@credativ.de>
Date: Tue, 1 Dec 2026 15:35:08 +0100
Subject: [PATCH] WIP: Fix deteriorating reltuples in successive VACUUM runs.

This adds yet another heuristic to vac_estimate_reltuples(), namely to keep the
old reltuples value if either less than 2% of the tuples were scanned or if the
tuple density is more than 3x lower than before.
---
 src/backend/commands/vacuum.c | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/src/backend/commands/vacuum.c b/src/backend/commands/vacuum.c
index 63f6b8a733a..3c0d6a77ccb 100644
--- a/src/backend/commands/vacuum.c
+++ b/src/backend/commands/vacuum.c
@@ -1372,6 +1372,7 @@ vac_estimate_reltuples(Relation relation,
 	BlockNumber sampleable_pages;
 	double		old_rel_tuples = relation->rd_rel->reltuples;
 	double		old_density;
+	double		new_density;
 	double		unscanned_pages;
 	double		total_tuples;
 
@@ -1418,15 +1419,27 @@ vac_estimate_reltuples(Relation relation,
 		 sampled_pages < (double) sampleable_pages * 0.02))
 		return old_rel_tuples;
 
+	/*
+	 * Similar to the above, but in case there are a lot of dead pages and
+	 * VACUUM scans only a few (less than 2%) tuples, or comes up with a much
+	 * lower (more than three times) density (tuples per page) than before, keep
+	 * the existing value as well.
+	 */
+	old_density = old_rel_tuples / old_rel_pages;
+	unscanned_pages = (double) sampleable_pages - (double) sampled_pages;
+	total_tuples = old_density * unscanned_pages + scanned_tuples;
+	new_density = total_tuples / total_pages;
+	if (old_rel_pages == total_pages &&
+		(scanned_tuples < (double) old_rel_tuples * 0.02 ||
+		 old_density / new_density > 3.0))
+		return old_rel_tuples;
+
 	/*
 	 * Okay, we've covered the corner cases.  The normal calculation is to
 	 * convert the old measurement to a density (tuples per page), then
 	 * estimate the number of tuples in the unscanned pages using that figure,
 	 * and finally add on the number of tuples in the scanned pages.
 	 */
-	old_density = old_rel_tuples / old_rel_pages;
-	unscanned_pages = (double) sampleable_pages - (double) sampled_pages;
-	total_tuples = old_density * unscanned_pages + scanned_tuples;
 	return floor(total_tuples + 0.5);
 }
 
-- 
2.47.3

