From c54b1d87323a5033a2a617dc7a91f8eef6f9bc19 Mon Sep 17 00:00:00 2001
From: JiaoShuntian <jiaoshuntian@highgo.com>
Date: Thu, 26 Nov 2026 17:05:18 +0800
Subject: [PATCH v1] Avoid reltuples drift during partial heap vacuums

Repeated scans of recently dead tuples can drive reltuples down.
Keeping the prior estimate as a floor in this case can also preserve
an overestimate after a real deletion.

Discussion: https://postgr.es/m/18773-666a02177904ef98@postgresql.org
---
 src/backend/access/heap/vacuumlazy.c | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/src/backend/access/heap/vacuumlazy.c b/src/backend/access/heap/vacuumlazy.c
index 1393c57ad8f..71a509239b3 100644
--- a/src/backend/access/heap/vacuumlazy.c
+++ b/src/backend/access/heap/vacuumlazy.c
@@ -1602,6 +1602,21 @@ lazy_scan_heap(LVRelState *vacrel)
 							   vacrel->scanned_new_pages,
 							   vacrel->live_tuples);
 
+	/*
+	 * A pinned cleanup horizon can make successive VACUUMs revisit pages
+	 * containing mostly recently dead tuples while skipping all-visible
+	 * pages.  Feeding each lower estimate back into the next scan would
+	 * repeatedly discount the same live tuples on the skipped pages.
+	 * If the table hasn't changed size and we removed no tuples, don't
+	 * lower a known estimate on the strength of such a partial scan.
+	 */
+	if (vacrel->scanned_pages < rel_pages &&
+		rel_pages == vacrel->rel->rd_rel->relpages &&
+		vacrel->tuples_deleted == 0 &&
+		vacrel->recently_dead_tuples > vacrel->live_tuples)
+		vacrel->new_live_tuples = Max(vacrel->new_live_tuples,
+									  vacrel->rel->rd_rel->reltuples);
+
 	/*
 	 * Also compute the total number of surviving heap entries.  In the
 	 * (unlikely) scenario that new_live_tuples is -1, take it as zero.
-- 
2.43.0

