From 2414028ab64bcffccfee75790a15b5960de8d095 Mon Sep 17 00:00:00 2001 From: David Rowley Date: Tue, 6 Oct 2026 01:22:23 +1300 Subject: [PATCH] Fix tuplesort memory accounting for datum sorts on byref types 6ed83d5fa made it so tuplesorts could use a bump.c memory allocator for non-bounded sorts in order to save memory and increase performance. That commit didn't get the memory accounting correct for datum sorts and mistakenly passed 0 bytes to tuplesort_puttuple_common(). That was correct for byval types, but failed to take into account palloc'd memory for byref types. Fix by using datumGetSize() when using the bump allocator and by using GetMemoryChunkSpace() when not. Backpatch to v17, where 6ed83d5fa was added. Author: Mario Karuza Reviewed-by: David Rowley Reviewed-by: Joao Detomini Discussion: https://postgr.es/m/e9f9f54337cd86a982837763958518cdbf08863c.camel%40icloud.com Backpatch-through: 17 --- src/backend/utils/sort/tuplesortvariants.c | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/backend/utils/sort/tuplesortvariants.c b/src/backend/utils/sort/tuplesortvariants.c index 05a853caa36..b12e46883fa 100644 --- a/src/backend/utils/sort/tuplesortvariants.c +++ b/src/backend/utils/sort/tuplesortvariants.c @@ -829,6 +829,7 @@ tuplesort_putdatum(Tuplesortstate *state, Datum val, bool isNull) MemoryContext oldcontext = MemoryContextSwitchTo(base->tuplecontext); TuplesortDatumArg *arg = (TuplesortDatumArg *) base->arg; SortTuple stup; + Size tuplen; /* * Pass-by-value types or null values are just stored directly in @@ -851,17 +852,26 @@ tuplesort_putdatum(Tuplesortstate *state, Datum val, bool isNull) stup.datum1 = !isNull ? val : (Datum) 0; stup.isnull1 = isNull; stup.tuple = NULL; /* no separate storage */ + tuplen = 0; } else { stup.isnull1 = false; stup.datum1 = datumCopy(val, false, arg->datumTypeLen); stup.tuple = DatumGetPointer(stup.datum1); + + /* GetMemoryChunkSpace is not supported for bump contexts */ + if (TupleSortUseBumpTupleCxt(base->sortopt)) + tuplen = MAXALIGN(datumGetSize(PointerGetDatum(stup.tuple), + false, + arg->datumTypeLen)); + else + tuplen = GetMemoryChunkSpace(stup.tuple); } tuplesort_puttuple_common(state, &stup, base->tuples && - base->sortKeys->abbrev_converter && !isNull, 0); + base->sortKeys->abbrev_converter && !isNull, tuplen); MemoryContextSwitchTo(oldcontext); }