From d30a947a83f181e05facbc2c51070da1f6f8b5f0 Mon Sep 17 00:00:00 2001 From: Chengpeng Yan Date: Thu, 3 Dec 2026 21:58:27 +0800 Subject: [PATCH v2 2/2] Avoid copying tuples that a bounded sort will discard Once a bounded sort's heap is full, most input tuples lose to the root and are freed right after being copied. Compare the leading key, read with slot_getattr() so that every slot type is covered, with the root first, and copy only the tuples that may be kept; when the leading keys tie, the remaining keys decide after the copy. --- src/backend/utils/sort/tuplesortvariants.c | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/src/backend/utils/sort/tuplesortvariants.c b/src/backend/utils/sort/tuplesortvariants.c index dbc8dedfd24..d589ce925a7 100644 --- a/src/backend/utils/sort/tuplesortvariants.c +++ b/src/backend/utils/sort/tuplesortvariants.c @@ -767,20 +767,36 @@ bounded_discard(TuplesortPublic *base, Datum datum1, bool isnull1) /* * Accept one tuple while collecting input data for sort. * - * Note that the input data is always copied; the caller need not save it. + * Note that the input data is copied if it is kept; the caller need not save + * it. */ void tuplesort_puttupleslot(Tuplesortstate *state, TupleTableSlot *slot) { TuplesortPublic *base = TuplesortstateGetPublic(state); - MemoryContext oldcontext = MemoryContextSwitchTo(base->tuplecontext); + MemoryContext oldcontext; TupleDesc tupDesc = (TupleDesc) base->arg; SortTuple stup; MinimalTuple tuple; HeapTupleData htup; Size tuplen; + /* in a bounded sort, avoid copying a tuple that would be discarded */ + if (base->boundedRoot != NULL) + { + bool isnull1; + Datum datum1 = slot_getattr(slot, base->sortKeys[0].ssup_attno, + &isnull1); + + if (bounded_discard(base, datum1, isnull1)) + { + CHECK_FOR_INTERRUPTS(); + return; + } + } + /* copy the tuple into sort storage */ + oldcontext = MemoryContextSwitchTo(base->tuplecontext); tuple = ExecCopySlotMinimalTuple(slot); stup.tuple = tuple; /* set up first-column key value */ -- 2.50.1 (Apple Git-155)