From cf601684ac54afe888d35154d2e14e2d37fd5912 Mon Sep 17 00:00:00 2001 From: Matthias van de Meent Date: Fri, 17 Jul 2026 18:48:00 +0200 Subject: [PATCH v1] Fix corrupted caches when we OOM getting the partition check --- src/backend/utils/cache/partcache.c | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/src/backend/utils/cache/partcache.c b/src/backend/utils/cache/partcache.c index 3107075c9ad..a4596ff8c2c 100644 --- a/src/backend/utils/cache/partcache.c +++ b/src/backend/utils/cache/partcache.c @@ -411,14 +411,31 @@ generate_partition_qual(Relation rel) */ if (result != NIL) { - rel->rd_partcheckcxt = AllocSetContextCreate(CacheMemoryContext, - "partition constraint", - ALLOCSET_SMALL_SIZES); - MemoryContextCopyAndSetIdentifier(rel->rd_partcheckcxt, + /* + * Take care to order operations so that allocation errors don't + * leave the catcache in an invalid state; first allocate everything + * into a transactional context, then associate it with CacheContext + * and update the relation data. This also avoids leaking memory if + * we ever hit OOM here. + */ + List *partcheck; + MemoryContext partctx; + + partctx = AllocSetContextCreate(CurrentMemoryContext, + "partition constraint", + ALLOCSET_SMALL_SIZES); + MemoryContextCopyAndSetIdentifier(partctx, RelationGetRelationName(rel)); - oldcxt = MemoryContextSwitchTo(rel->rd_partcheckcxt); - rel->rd_partcheck = copyObject(result); + + oldcxt = MemoryContextSwitchTo(partctx); + partcheck = copyObject(result); MemoryContextSwitchTo(oldcxt); + + /* finally, link the allocations and memctx into the right places */ + MemoryContextSetParent(partctx, CacheMemoryContext); + + rel->rd_partcheckcxt = partctx; + rel->rd_partcheck = partcheck; } else rel->rd_partcheck = NIL; -- 2.50.1 (Apple Git-155)