From 85adc584e2bd3ee6ce1899929fc60afb709b4772 Mon Sep 17 00:00:00 2001 From: David Rowley Date: Tue, 6 Oct 2026 01:20:57 +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 95b9ff9d39a..c648c78455a 100644 --- a/src/backend/utils/sort/tuplesortvariants.c +++ b/src/backend/utils/sort/tuplesortvariants.c @@ -939,6 +939,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 @@ -961,17 +962,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); }