From e44443b5036ff392ebb8bd74334a02cab351b332 Mon Sep 17 00:00:00 2001
From: John Naylor <john.naylor@postgresql.org>
Date: Wed, 2 Dec 2026 13:56:58 +0700
Subject: [PATCH v1] Free the displaced heap top when switching to a bounded
 heap sort

make_bounded_heap() inserts the first N tuples into the heap.  Once the
heap is full, it compares each remaining tuple with the root.  A tuple
that falls outside the first N rows is discarded and freed.  Otherwise
the tuple replaces the root, and the old root drops out of the heap.
That old root was not freed. This presented in "ORDER BY ... LIMIT N"
queries, most notably when the input arrived in reverse order. Oversight
in commit 24598337c.

Discussion: https://postgr.es/m/

Backpatch-through: 15
---
 src/backend/utils/sort/tuplesort.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c
index 31ce2e661e3..9be6c989766 100644
--- a/src/backend/utils/sort/tuplesort.c
+++ b/src/backend/utils/sort/tuplesort.c
@@ -2528,7 +2528,10 @@ make_bounded_heap(Tuplesortstate *state)
 				CHECK_FOR_INTERRUPTS();
 			}
 			else
+			{
+				free_sort_tuple(state, &state->memtuples[0]);
 				tuplesort_heap_replace_top(state, &state->memtuples[i]);
+			}
 		}
 	}
 
-- 
2.56.1

