From f75a7c14155a953af56ba3fda16e66ed8f4065d8 Mon Sep 17 00:00:00 2001 From: Michael Paquier Date: Sat, 18 Jul 2026 11:47:00 +0900 Subject: [PATCH] Improve pgstat_get_entry_ref_cached() behavior on OOMs --- src/backend/utils/activity/pgstat_shmem.c | 26 ++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/src/backend/utils/activity/pgstat_shmem.c b/src/backend/utils/activity/pgstat_shmem.c index 5ea3f1973f90..22c6ed4981a3 100644 --- a/src/backend/utils/activity/pgstat_shmem.c +++ b/src/backend/utils/activity/pgstat_shmem.c @@ -15,6 +15,7 @@ #include "pgstat.h" #include "storage/shmem.h" #include "storage/subsystems.h" +#include "utils/injection_point.h" #include "utils/memutils.h" #include "utils/pgstat_internal.h" @@ -432,9 +433,28 @@ 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); + + /* emulate OOM */ + if (IS_INJECTION_POINT_ATTACHED("pgstat-entry-ref-oom")) + entry_ref = NULL; + + 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; -- 2.55.0