From 290cc849f222680bf5f69303ed368ada6bb3eed4 Mon Sep 17 00:00:00 2001
From: Floris van Nee <florisvannee@optiver.com>
Date: Sun, 2 Jun 2024 22:35:44 +0200
Subject: [PATCH v2] Notify stats gc when dropping logical replication slot

pgstat_drop_replslot calls pgstat_drop_entry without checking the
result. If pgstat_drop_entry cannot free the entry from shared memory
completely, the gc function must be called to flag it for other
backends. This is similar to what AtEOXact_PgStat_DroppedStats and
similar functions do.
---
 src/backend/utils/activity/pgstat_replslot.c |  5 +++--
 src/backend/utils/activity/pgstat_shmem.c    | 11 +++++++++++
 2 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/src/backend/utils/activity/pgstat_replslot.c b/src/backend/utils/activity/pgstat_replslot.c
index 889e86ac5a..da11b86744 100644
--- a/src/backend/utils/activity/pgstat_replslot.c
+++ b/src/backend/utils/activity/pgstat_replslot.c
@@ -157,8 +157,9 @@ pgstat_drop_replslot(ReplicationSlot *slot)
 {
 	Assert(LWLockHeldByMeInMode(ReplicationSlotAllocationLock, LW_EXCLUSIVE));
 
-	pgstat_drop_entry(PGSTAT_KIND_REPLSLOT, InvalidOid,
-					  ReplicationSlotIndex(slot));
+	if (!pgstat_drop_entry(PGSTAT_KIND_REPLSLOT, InvalidOid,
+						   ReplicationSlotIndex(slot)))
+		pgstat_request_entry_refs_gc();
 }
 
 /*
diff --git a/src/backend/utils/activity/pgstat_shmem.c b/src/backend/utils/activity/pgstat_shmem.c
index 91591da395..4a4b69891d 100644
--- a/src/backend/utils/activity/pgstat_shmem.c
+++ b/src/backend/utils/activity/pgstat_shmem.c
@@ -855,6 +855,17 @@ pgstat_drop_database_and_contents(Oid dboid)
 		pgstat_request_entry_refs_gc();
 }
 
+/*
+ * Drop a single stats entry.
+ *
+ * This routine returns false if the stats entry of the dropped object could
+ * not be freed, true otherwise.
+ *
+ * The callers of this function should call pgstat_request_entry_refs_gc()
+ * if the stats entry could not be freed, to ensure that this entry's memory
+ * can be reclaimed later by a different backend calling
+ * pgstat_gc_entry_refs().
+ */
 bool
 pgstat_drop_entry(PgStat_Kind kind, Oid dboid, Oid objoid)
 {
-- 
2.43.0

