]> git.ipfire.org Git - thirdparty/postgresql.git/commitdiff
Improve pgstat_get_entry_ref_cached() behavior on out-of-memory errors
authorMichael Paquier <michael@paquier.xyz>
Mon, 20 Jul 2026 06:52:18 +0000 (15:52 +0900)
committerMichael Paquier <michael@paquier.xyz>
Mon, 20 Jul 2026 06:52:18 +0000 (15:52 +0900)
A failure in allocating a new cache entry in the backend-level hash
table holding references to shared stats entries would leave the table
in an inconsistent state, crash or FATAL at session exit, depending on
if there are pending stats.

Rather than leaving things in an inconsistent state on OOM, the code is
switched to use MemoryContextAllocExtended(MCXT_ALLOC_NO_OOM), so as an
allocation failure leads to a cleanup of the hash table before issuing
the allocation error.

The problem is unlikely going to show up in practice, so no backpatch is
done.  Note that shared memory is not impacted, only a backend-level
hash table.

Reported-by: Alex Masterov <amasterov@gmail.com>
Discussion: https://postgr.es/m/CA+8z=zumV9sscgK=j1Es+-564maVoO9CMDdB9CsW9=FCziCj3w@mail.gmail.com

src/backend/utils/activity/pgstat_shmem.c

index 5ea3f1973f90d06d9d8d5436999b52e0bbbdb1f5..8511c25fd29055b3efea84ca8c8c1a80dbc7e59d 100644 (file)
@@ -432,9 +432,23 @@ pgstat_get_entry_ref_cached(PgStat_HashKey key, PgStat_EntryRef **entry_ref_p)
        {
                PgStat_EntryRef *entry_ref;
 
-               cache_entry->entry_ref = entry_ref =
-                       MemoryContextAlloc(pgStatSharedRefContext,
-                                                          sizeof(PgStat_EntryRef));
+               entry_ref = MemoryContextAllocExtended(pgStatSharedRefContext,
+                                                                                          sizeof(PgStat_EntryRef),
+                                                                                          MCXT_ALLOC_NO_OOM);
+               if (unlikely(entry_ref == NULL))
+               {
+                       /*
+                        * Clean the hash entry to keep the table consistent in the
+                        * backend.
+                        */
+                       pgstat_entry_ref_hash_delete(pgStatEntryRefHash, key);
+
+                       ereport(ERROR,
+                                       (errcode(ERRCODE_OUT_OF_MEMORY),
+                                        errmsg("out of memory")));
+               }
+
+               cache_entry->entry_ref = entry_ref;
                entry_ref->shared_stats = NULL;
                entry_ref->shared_entry = NULL;
                entry_ref->pending = NULL;