From 44c23bb260543ce160fc4f6b7993ea6d4ed5da9b Mon Sep 17 00:00:00 2001 From: Sai Pranav Date: Sat, 21 Nov 2026 08:23:14 +0000 Subject: [PATCH v1 REL_18 v1] Fix memory leak of skip array elements across btree rescans A skip array on a pass-by-reference type keeps a copy of its current element in sk_argument. The copy is made in the caller's memory context, and it was freed only when the array advanced to another element. On a rescan the key was rebuilt without freeing it, and btendscan didn't free it either, so the inner side of a nested loop that skip-scans a uuid or text column leaked one element per rescan until the end of the query. Free these elements in btrescan and btendscan. btbeginscan now sets numArrayKeys, which btrescan reads before setting it. Reported-by: Allen Hsu Discussion: https://postgr.es/m/19917-61cc2f6823e22810@postgresql.org Backpatch-through: 18 --- src/backend/access/nbtree/nbtree.c | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/backend/access/nbtree/nbtree.c b/src/backend/access/nbtree/nbtree.c index 4d83431056..e7cc48a0e1 100644 --- a/src/backend/access/nbtree/nbtree.c +++ b/src/backend/access/nbtree/nbtree.c @@ -365,6 +365,7 @@ btbeginscan(Relation rel, int nkeys, int norderbys) so->oppositeDirCheck = false; so->arrayKeys = NULL; so->orderProcs = NULL; + so->numArrayKeys = 0; so->arrayContext = NULL; so->killedItems = NULL; /* until needed */ @@ -384,6 +385,27 @@ btbeginscan(Relation rel, int nkeys, int norderbys) return scan; } +/* + * Free the current element of each skip array on a pass-by-reference type. + * These copies are made in the caller's memory context, not in arrayContext, + * so nothing else would free them before the end of the query. + */ +static void +_bt_free_skiparray_elems(BTScanOpaque so) +{ + for (int i = 0; i < so->numArrayKeys; i++) + { + BTArrayKeyInfo *array = &so->arrayKeys[i]; + ScanKey skey = &so->keyData[array->scan_key]; + + if (!(skey->sk_flags & SK_BT_SKIP) || array->attbyval) + continue; + if (skey->sk_argument) + pfree(DatumGetPointer(skey->sk_argument)); + skey->sk_argument = (Datum) 0; + } +} + /* * btrescan() -- rescan an index relation */ @@ -465,6 +487,7 @@ btrescan(IndexScanDesc scan, ScanKey scankey, int nscankeys, */ if (scankey && scan->numberOfKeys > 0) memcpy(scan->keyData, scankey, scan->numberOfKeys * sizeof(ScanKeyData)); + _bt_free_skiparray_elems(so); so->numberOfKeys = 0; /* until _bt_preprocess_keys sets it */ so->numArrayKeys = 0; /* ditto */ } @@ -492,6 +515,7 @@ btendscan(IndexScanDesc scan) /* No need to invalidate positions, the RAM is about to be freed. */ /* Release storage */ + _bt_free_skiparray_elems(so); if (so->keyData != NULL) pfree(so->keyData); /* so->arrayKeys and so->orderProcs are in arrayContext */ -- 2.50.1 (Apple Git-155)