Prevent inconsistent use of stats entry for replication slots
authorMichael Paquier <[email protected]>
Wed, 5 Jun 2024 23:47:40 +0000 (08:47 +0900)
committerMichael Paquier <[email protected]>
Wed, 5 Jun 2024 23:47:40 +0000 (08:47 +0900)
Concurrent activity around replication slot creation and drop could
cause a replication slot to use a stats entry it should not have used
when created, triggering an assertion failure when retrieving an
inconsistent entry from the dshash table used by the stats facility.

The issue is that pgstat_drop_replslot() calls pgstat_drop_entry()
without checking the result.  If pgstat_drop_entry() cannot free the
entry related to the object dropped, pgstat_request_entry_refs_gc()
should be called.  AtEOXact_PgStat_DroppedStats() and surrounding
routines dropping stats entries already do that.

This is documented in pgstat_internal.h, but let's add a comment at the
top of pgstat_drop_entry() as that can be easy to miss.

Reported-by: Alexander Lakhin
Author: Floris Van Nee
Analyzed-by: Andres Freund
Discussion: https://postgr.es/m/17947-b9554521ad963c9c@postgresql.org
Backpatch-through: 15

src/backend/utils/activity/pgstat_replslot.c
src/backend/utils/activity/pgstat_shmem.c

index 889e86ac5ace6644742a24a6255402070234e882..da11b867445955fefcf851a10203705be8d73ed5 100644 (file)
@@ -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();
 }
 
 /*
index 91591da3958f48a8c4484dce41e521242634879d..4a4b69891d3cfcbad66ab5e2ed5d49c9da688283 100644 (file)
@@ -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)
 {