From f58198415cf38d8cf29c9d28e77fb9c251a6e951 Mon Sep 17 00:00:00 2001
From: Rustam Khamidullin <r.khamidullin@postgrespro.ru>
Date: Fri, 24 Jul 2026 11:10:18 +0700
Subject: [PATCH] Fix reversed sort order in autovacuum's db_comparator()

Commit 3b42bdb4716 inadvertently reversed the sort order of databases
in rebuild_database_list().  The original comparator sorted in
descending order by adl_score, but the commit replaced the manual
comparison with pg_cmp_s32(a, b), which produces ascending order.
As a result, the scheduling order of databases for autovacuum was
reversed each time the database list was rebuilt.

Restore the intended descending order by swapping the arguments to
pg_cmp_s32().  Update the surrounding comments to make the expected
sort direction explicit.
---
 src/backend/postmaster/autovacuum.c | 11 +++++++----
 1 file changed, 7 insertions(+), 4 deletions(-)

diff --git a/src/backend/postmaster/autovacuum.c b/src/backend/postmaster/autovacuum.c
index 45abf48768a..e0c2c9b306f 100644
--- a/src/backend/postmaster/autovacuum.c
+++ b/src/backend/postmaster/autovacuum.c
@@ -1068,7 +1068,10 @@ rebuild_database_list(Oid newdb)
 		while ((db = hash_seq_search(&seq)) != NULL)
 			memcpy(&(dbary[i++]), db, sizeof(avl_dbase));
 
-		/* sort the array */
+		/*
+		 * Sort the array in descending order so that the databases with the
+		 * highest score get the least adl_next_worker time.
+		 */
 		qsort(dbary, nelems, sizeof(avl_dbase), db_comparator);
 
 		/*
@@ -1109,12 +1112,12 @@ rebuild_database_list(Oid newdb)
 	MemoryContextSwitchTo(oldcxt);
 }
 
-/* qsort comparator for avl_dbase, using adl_score */
+/* qsort comparator for avl_dbase, using adl_score in descending order */
 static int
 db_comparator(const void *a, const void *b)
 {
-	return pg_cmp_s32(((const avl_dbase *) a)->adl_score,
-					  ((const avl_dbase *) b)->adl_score);
+	return pg_cmp_s32(((const avl_dbase *) b)->adl_score,
+					  ((const avl_dbase *) a)->adl_score);
 }
 
 /*
-- 
2.54.0

