While reviewing bounded-sort improvements, I found a separate issue:
make_bounded_heap() doesn't free the root tuple when replaced (and
hasn't for 10 years), which shows up as increased memory reporting,
especially with inputs in reverse order. In the attached repro, we see

master:
                          QUERY PLAN
--------------------------------------------------------------
 Limit (actual rows=5000.00 loops=1)
   ->  Sort (actual rows=5000.00 loops=1)
         Sort Key: k DESC
         Sort Method: top-N heapsort  Memory: 10542kB
         ->  Seq Scan on mem01 (actual rows=20000.00 loops=1)
(5 rows)

patch:
                          QUERY PLAN
--------------------------------------------------------------
 Limit (actual rows=5000.00 loops=1)
   ->  Sort (actual rows=5000.00 loops=1)
         Sort Key: k DESC
         Sort Method: top-N heapsort  Memory: 5463kB
         ->  Seq Scan on mem01 (actual rows=20000.00 loops=1)
(5 rows)

It's academic from the OS perspective, since the blocks can't be freed
until the sort ends, but the user-visible anomaly still seems worth
backpatching. Barring objections I'll commit the attached fix soon.

--
John Naylor
Amazon Web Services
From e44443b5036ff392ebb8bd74334a02cab351b332 Mon Sep 17 00:00:00 2001
From: John Naylor <[email protected]>
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

Attachment: bounded-sort-leak.sql
Description: application/sql

Reply via email to