From 8f5c5a0fc99229200105a3acd10b3c1e5aa5133c Mon Sep 17 00:00:00 2001
From: Chengpeng Yan <chengpeng_yan@outlook.com>
Date: Sun, 29 Nov 2026 14:19:03 +0800
Subject: [PATCH v1 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 of a
heap or minimal tuple 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/tuplesort.c         |  23 ++++-
 src/backend/utils/sort/tuplesortvariants.c | 113 +++++++++++++++++++--
 src/include/utils/tuplesort.h              |   4 +-
 src/test/regress/expected/tuplesort.out    |  11 ++
 src/test/regress/sql/tuplesort.sql         |   2 +
 5 files changed, 136 insertions(+), 17 deletions(-)

diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c
index a688afafd7f..16a9ebe70b8 100644
--- a/src/backend/utils/sort/tuplesort.c
+++ b/src/backend/utils/sort/tuplesort.c
@@ -1071,24 +1071,37 @@ noalloc:
 }
 
 /*
- * Replace the root of the full bounded heap with a copied tuple already
- * known to sort before it.
+ * Add a copied tuple to the full bounded heap, given how its leading key
+ * compared with the root's.
  */
 void
 tuplesort_bounded_puttuple(Tuplesortstate *state, SortTuple *tuple,
-						   Size tuplen)
+						   Size tuplen, TuplesortBoundedCheck check)
 {
 	MemoryContext oldcontext = MemoryContextSwitchTo(state->base.sortcontext);
 
 	Assert(state->status == TSS_BOUNDED);
 	Assert(state->base.boundedRoot == &state->memtuples[0]);
+	Assert(check == TUPLESORT_BOUNDED_REPLACE ||
+		   (check == TUPLESORT_BOUNDED_TIE && state->base.nKeys > 1));
 
 	/* account for the memory used for this tuple */
 	USEMEM(state, tuplen);
 	state->tupleMem += tuplen;
 
-	free_sort_tuple(state, &state->memtuples[0]);
-	tuplesort_heap_replace_top(state, tuple);
+	/* a tie on the leading key is settled by the remaining keys */
+	if (check == TUPLESORT_BOUNDED_TIE &&
+		state->base.comparetup_tiebreak(tuple, &state->memtuples[0],
+										state) <= 0)
+	{
+		free_sort_tuple(state, tuple);
+		CHECK_FOR_INTERRUPTS();
+	}
+	else
+	{
+		free_sort_tuple(state, &state->memtuples[0]);
+		tuplesort_heap_replace_top(state, tuple);
+	}
 
 	MemoryContextSwitchTo(oldcontext);
 }
diff --git a/src/backend/utils/sort/tuplesortvariants.c b/src/backend/utils/sort/tuplesortvariants.c
index bc6a2e18a29..f823c6215de 100644
--- a/src/backend/utils/sort/tuplesortvariants.c
+++ b/src/backend/utils/sort/tuplesortvariants.c
@@ -37,6 +37,12 @@
 #include "utils/rel.h"
 #include "utils/tuplesort.h"
 
+/*
+ * Stride for read_tuple_lines(): cache lines are at least 64 bytes on common
+ * systems.
+ */
+#define TUPLE_READ_STRIDE	64
+
 
 /* sort-type codes for sort__start probes */
 #define HEAP_SORT		0
@@ -752,8 +758,6 @@ bounded_check(TuplesortPublic *base, Datum datum1, bool isnull1)
 
 	/* tuplesort_set_bound() disabled abbreviated keys */
 	Assert(base->sortKeys->abbrev_converter == NULL);
-	/* one sort key, so a tie is final and the input is discarded */
-	Assert(base->nKeys == 1);
 
 	/* Use the same context as tuplesort_puttuple_common(). */
 	oldcontext = MemoryContextSwitchTo(base->sortcontext);
@@ -766,14 +770,75 @@ bounded_check(TuplesortPublic *base, Datum datum1, bool isnull1)
 	if (compare > 0)
 		return TUPLESORT_BOUNDED_REPLACE;
 
+	if (compare == 0 && base->nKeys > 1)
+		return TUPLESORT_BOUNDED_TIE;
+
 	CHECK_FOR_INTERRUPTS();
 	return TUPLESORT_BOUNDED_DISCARD;
 }
 
+/*
+ * Read every cache line of the given range, so that the sparse reads that
+ * follow do not each wait on memory.
+ */
+static inline void
+read_tuple_lines(const void *start, uint32 len)
+{
+	const volatile char *p = (const volatile char *) start;
+
+	Assert(len > 0);
+
+	/* volatile keeps the reads; (void) silences the unused-value warning */
+	for (uint32 off = 0; off < len; off += TUPLE_READ_STRIDE)
+		(void) p[off];
+
+	/* the start may be unaligned; touch the last line too */
+	(void) p[len - 1];
+}
+
+/*
+ * Decide whether a bounded sort will keep this slot's tuple before copying
+ * it, and return its leading key.  Return UNKNOWN when the tuple cannot be
+ * checked this way.
+ */
+static TuplesortBoundedCheck
+puttupleslot_check(TuplesortPublic *base, TupleTableSlot *slot,
+				   Datum *datum1, bool *isnull1)
+{
+	AttrNumber	attno = base->sortKeys[0].ssup_attno;
+	HeapTupleData src;
+
+	Assert(attno > 0);
+
+	if (slot->tts_ops->get_heap_tuple != NULL)
+		src = *ExecFetchSlotHeapTuple(slot, false, NULL);
+	else if (slot->tts_ops->get_minimal_tuple != NULL)
+	{
+		MinimalTuple mtup = ExecFetchSlotMinimalTuple(slot, NULL);
+
+		/* make the compact tuple readable by heap_getattr() */
+		src.t_len = mtup->t_len + MINIMAL_TUPLE_OFFSET;
+		src.t_data = (HeapTupleHeader) ((char *) mtup - MINIMAL_TUPLE_OFFSET);
+	}
+	else
+	{
+		/* no physical tuple to check; use the usual copy path */
+		return TUPLESORT_BOUNDED_UNKNOWN;
+	}
+
+	read_tuple_lines((char *) src.t_data + MINIMAL_TUPLE_OFFSET,
+					 src.t_len - MINIMAL_TUPLE_OFFSET);
+
+	*datum1 = heap_getattr(&src, attno, (TupleDesc) base->arg, isnull1);
+
+	return bounded_check(base, *datum1, *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)
@@ -785,6 +850,20 @@ tuplesort_puttupleslot(Tuplesortstate *state, TupleTableSlot *slot)
 	MinimalTuple tuple;
 	HeapTupleData htup;
 	Size		tuplen;
+	TuplesortBoundedCheck check = TUPLESORT_BOUNDED_UNKNOWN;
+	Datum		datum1 = (Datum) 0;
+	bool		isnull1 = false;
+
+	/* in a bounded sort, avoid copying a tuple that would be discarded */
+	if (base->boundedRoot != NULL)
+	{
+		check = puttupleslot_check(base, slot, &datum1, &isnull1);
+		if (check == TUPLESORT_BOUNDED_DISCARD)
+		{
+			MemoryContextSwitchTo(oldcontext);
+			return;
+		}
+	}
 
 	/* copy the tuple into sort storage */
 	tuple = ExecCopySlotMinimalTuple(slot);
@@ -792,10 +871,19 @@ tuplesort_puttupleslot(Tuplesortstate *state, TupleTableSlot *slot)
 	/* set up first-column key value */
 	htup.t_len = tuple->t_len + MINIMAL_TUPLE_OFFSET;
 	htup.t_data = (HeapTupleHeader) ((char *) tuple - MINIMAL_TUPLE_OFFSET);
-	stup.datum1 = heap_getattr(&htup,
-							   base->sortKeys[0].ssup_attno,
-							   tupDesc,
-							   &stup.isnull1);
+	if (check != TUPLESORT_BOUNDED_UNKNOWN &&
+		TupleDescCompactAttr(tupDesc,
+							 base->sortKeys[0].ssup_attno - 1)->attbyval)
+	{
+		/* a pass-by-value key read for the check is still valid */
+		stup.datum1 = datum1;
+		stup.isnull1 = isnull1;
+	}
+	else
+		stup.datum1 = heap_getattr(&htup,
+								   base->sortKeys[0].ssup_attno,
+								   tupDesc,
+								   &stup.isnull1);
 
 	/* GetMemoryChunkSpace is not supported for bump contexts */
 	if (TupleSortUseBumpTupleCxt(base->sortopt))
@@ -803,9 +891,12 @@ tuplesort_puttupleslot(Tuplesortstate *state, TupleTableSlot *slot)
 	else
 		tuplen = GetMemoryChunkSpace(tuple);
 
-	tuplesort_puttuple_common(state, &stup,
-							  base->sortKeys->abbrev_converter &&
-							  !stup.isnull1, tuplen);
+	if (check == TUPLESORT_BOUNDED_UNKNOWN)
+		tuplesort_puttuple_common(state, &stup,
+								  base->sortKeys->abbrev_converter &&
+								  !stup.isnull1, tuplen);
+	else
+		tuplesort_bounded_puttuple(state, &stup, tuplen, check);
 
 	MemoryContextSwitchTo(oldcontext);
 }
@@ -1037,7 +1128,7 @@ tuplesort_putdatum(Tuplesortstate *state, Datum val, bool isNull)
 								  base->sortKeys->abbrev_converter && !isNull,
 								  tuplen);
 	else
-		tuplesort_bounded_puttuple(state, &stup, tuplen);
+		tuplesort_bounded_puttuple(state, &stup, tuplen, check);
 
 	MemoryContextSwitchTo(oldcontext);
 }
diff --git a/src/include/utils/tuplesort.h b/src/include/utils/tuplesort.h
index 9ff0338ffa5..bb4637d5b26 100644
--- a/src/include/utils/tuplesort.h
+++ b/src/include/utils/tuplesort.h
@@ -356,10 +356,12 @@ typedef enum TuplesortBoundedCheck
 	TUPLESORT_BOUNDED_UNKNOWN,	/* not compared; add the tuple as usual */
 	TUPLESORT_BOUNDED_DISCARD,
 	TUPLESORT_BOUNDED_REPLACE,
+	TUPLESORT_BOUNDED_TIE,		/* leading keys tie; later keys decide */
 } TuplesortBoundedCheck;
 
 extern void tuplesort_bounded_puttuple(Tuplesortstate *state,
-									   SortTuple *tuple, Size tuplen);
+									   SortTuple *tuple, Size tuplen,
+									   TuplesortBoundedCheck check);
 extern void tuplesort_puttuple_common(Tuplesortstate *state,
 									  SortTuple *tuple, bool useAbbrev,
 									  Size tuplen);
diff --git a/src/test/regress/expected/tuplesort.out b/src/test/regress/expected/tuplesort.out
index fc1321bf443..f191f86ec17 100644
--- a/src/test/regress/expected/tuplesort.out
+++ b/src/test/regress/expected/tuplesort.out
@@ -133,6 +133,17 @@ SELECT abort_increasing, noabort_increasing FROM abbrev_abort_uuids ORDER BY noa
  00000000-0000-0000-0000-000000010009 | 00000000-0000-0000-0000-000000010009
 (5 rows)
 
+-- bounded sort fed heap tuples directly by a scan
+SELECT * FROM abbrev_abort_uuids ORDER BY noabort_increasing DESC NULLS LAST LIMIT 5;
+  id   |           abort_increasing           |           abort_decreasing           |          noabort_increasing          |          noabort_decreasing          
+-------+--------------------------------------+--------------------------------------+--------------------------------------+--------------------------------------
+ 10009 | 00000000-0000-0000-0000-000000010008 | 00000000-0000-0000-0000-000000009992 | 00010008-0000-0000-0000-000000010008 | 00009992-0000-0000-0000-000000009992
+ 10008 | 00000000-0000-0000-0000-000000010007 | 00000000-0000-0000-0000-000000009993 | 00010007-0000-0000-0000-000000010007 | 00009993-0000-0000-0000-000000009993
+ 10007 | 00000000-0000-0000-0000-000000010006 | 00000000-0000-0000-0000-000000009994 | 00010006-0000-0000-0000-000000010006 | 00009994-0000-0000-0000-000000009994
+ 10006 | 00000000-0000-0000-0000-000000010005 | 00000000-0000-0000-0000-000000009995 | 00010005-0000-0000-0000-000000010005 | 00009995-0000-0000-0000-000000009995
+ 10005 | 00000000-0000-0000-0000-000000010004 | 00000000-0000-0000-0000-000000009996 | 00010004-0000-0000-0000-000000010004 | 00009996-0000-0000-0000-000000009996
+(5 rows)
+
 ----
 -- Check index creation uses of tuplesort wrt. abbreviated keys
 ----
diff --git a/src/test/regress/sql/tuplesort.sql b/src/test/regress/sql/tuplesort.sql
index 8476e594e6c..826cdc1d15d 100644
--- a/src/test/regress/sql/tuplesort.sql
+++ b/src/test/regress/sql/tuplesort.sql
@@ -47,6 +47,8 @@ SELECT noabort_increasing, noabort_decreasing FROM abbrev_abort_uuids ORDER BY n
 -- bounded sort (disables abbreviated keys)
 SELECT abort_increasing, noabort_increasing FROM abbrev_abort_uuids ORDER BY abort_increasing LIMIT 5;
 SELECT abort_increasing, noabort_increasing FROM abbrev_abort_uuids ORDER BY noabort_increasing NULLS FIRST LIMIT 5;
+-- bounded sort fed heap tuples directly by a scan
+SELECT * FROM abbrev_abort_uuids ORDER BY noabort_increasing DESC NULLS LAST LIMIT 5;
 
 
 ----
-- 
2.50.1 (Apple Git-155)

