From c2c2603353e1a071a6512936e4b354d4c60b3e3a Mon Sep 17 00:00:00 2001 From: Greg Burd Date: Fri, 23 Oct 2026 07:36:15 -0400 Subject: [PATCH v4] Use quickselect instead of a heap for bounded sorts A bounded sort (ORDER BY ... LIMIT N) switches to a heap of N tuples once 2 * N tuples have accumulated in memory, and then pays O(log N) comparisons for every tuple that the heap admits. When N is large, or the input arrives in an order that admits most tuples, that per-tuple log N dominates; at large N the bounded heap can lose to an unbounded quicksort of the whole input. Replace the heap with quickselect. Keep a buffer of up to Max(2 * N, 1000) tuples and, whenever it fills, use quickselect to keep the N smallest and free the rest. A prune does O(buffer) work to drop (buffer - N) tuples, so the amortized cost is O(1) per tuple. An incoming tuple is still rejected with a single comparison against the largest survivor of the last prune (memtuples[bound - 1]), the same one comparison the heap makes against its root. At the end the survivors go through tuplesort_sort_memtuples(), which picks radix sort or the specialized qsort exactly as an unbounded sort does. On reversed input, where every tuple is admitted, this runs a large bounded sort in a fraction of the heap's time (roughly 0.2x at LIMIT 10000 in local tests); on random input it matches the heap, since there the first comparison rejects almost every tuple before it is buffered. LIMIT 1 and 2 on reversed input remain the one case where the heap is faster, because a select over the floor of 1000 tuples cannot beat one compare-and-replace per tuple; a running-minimum special case for N = 1 is left for a separate patch. The buffer never drops below TOPN_SELECT_MIN_BUFFER (1000) so that a small bound still amortizes the prune cost, and that floor fits inside the initial memtuples array, so the array is never grown past what the sort already allocated. If the buffer's own tuples fill work_mem, prune early at 2 * N; like the existing heap, a bounded sort may still exceed work_mem when later tuples are wider than earlier ones, since N of them must be kept. The heap code (make_bounded_heap / sort_bounded_heap) stays, but is now reached only when work_mem is already full at the 2 * N switch, so bounded sorts have one in-memory strategy rather than two. EXPLAIN reports the new method as "top-N quickselect", distinct from the "top-N heapsort" the retained heap path still reports. cost_sort() models it: each input tuple costs about one comparison to accept or reject, plus a linear amount of prune work amortized over the input and a final sort of the N survivors, which is strictly below the heap's old N * log2(2N) estimate. Rows that tie on every sort key can come out in a different order than the heap produced. SQL leaves that order unspecified, so this is not a correctness change, but it is user-visible: contrib/cube's regression test compared a sort-based ORDER BY c~>2 LIMIT 15 against the GiST-ordered result and relied on the heap's order for one tie, so a c~>4 tiebreaker is added there. A bump context is not used for the buffer. A rejected tuple is copied into the sort's tuple context before the bounded check runs and must then be freed, which a bump context cannot do per chunk; avoiding that needs the compare-before-copy change under discussion separately, so the buffer keeps the existing aset context. Bounded sorts run only in the leader (tuplesort_set_bound ignores the hint in parallel workers), which prune_bounded_select() asserts; a parallel ORDER BY ... LIMIT regression test guards that the serial assumption holds. Discussion: https://postgr.es/m/attQRRU-Yh-e6rKj@floki Change-Id: Ie7fef07ea466c088a97f0f71a18956574ea9c98c --- contrib/cube/expected/cube.out | 2 +- contrib/cube/sql/cube.sql | 2 +- doc/src/sgml/rules.sgml | 2 +- src/backend/optimizer/path/costsize.c | 22 +- src/backend/utils/sort/tuplesort.c | 211 +++++++++++++++++- src/include/executor/instrument_node.h | 3 +- .../regress/expected/incremental_sort.out | 20 +- src/test/regress/expected/subselect.out | 2 +- src/test/regress/expected/tuplesort.out | 92 ++++++++ src/test/regress/sql/tuplesort.sql | 74 ++++++ 10 files changed, 406 insertions(+), 24 deletions(-) diff --git a/contrib/cube/expected/cube.out b/contrib/cube/expected/cube.out index 47787c50bd9..5eb3d8f8fdc 100644 --- a/contrib/cube/expected/cube.out +++ b/contrib/cube/expected/cube.out @@ -1832,7 +1832,7 @@ SELECT c~>1, c FROM test_cube ORDER BY c~>1 LIMIT 15; -- ascending by left bound 240 | (337, 455),(240, 359) (15 rows) -SELECT c~>2, c FROM test_cube ORDER BY c~>2 LIMIT 15; -- ascending by right bound +SELECT c~>2, c FROM test_cube ORDER BY c~>2, c~>4 LIMIT 15; -- ascending by right bound (c~>4 breaks the tie at 270) ?column? | c ----------+--------------------------- 0 | (0, 100000) diff --git a/contrib/cube/sql/cube.sql b/contrib/cube/sql/cube.sql index eec90d21ee3..c4a83e95238 100644 --- a/contrib/cube/sql/cube.sql +++ b/contrib/cube/sql/cube.sql @@ -428,7 +428,7 @@ RESET extra_float_digits; SELECT *, c <=> '(100, 100),(500, 500)'::cube as dist FROM test_cube ORDER BY c <=> '(100, 100),(500, 500)'::cube LIMIT 5; SELECT *, c <#> '(100, 100),(500, 500)'::cube as dist FROM test_cube ORDER BY c <#> '(100, 100),(500, 500)'::cube LIMIT 5; SELECT c~>1, c FROM test_cube ORDER BY c~>1 LIMIT 15; -- ascending by left bound -SELECT c~>2, c FROM test_cube ORDER BY c~>2 LIMIT 15; -- ascending by right bound +SELECT c~>2, c FROM test_cube ORDER BY c~>2, c~>4 LIMIT 15; -- ascending by right bound (c~>4 breaks the tie at 270) SELECT c~>3, c FROM test_cube ORDER BY c~>3 LIMIT 15; -- ascending by lower bound SELECT c~>4, c FROM test_cube ORDER BY c~>4 LIMIT 15; -- ascending by upper bound SELECT c~>(-1), c FROM test_cube ORDER BY c~>(-1) LIMIT 15; -- descending by left bound diff --git a/doc/src/sgml/rules.sgml b/doc/src/sgml/rules.sgml index 9f9fa978f2d..6d926e948f1 100644 --- a/doc/src/sgml/rules.sgml +++ b/doc/src/sgml/rules.sgml @@ -1078,7 +1078,7 @@ SELECT word FROM words ORDER BY word <-> 'caterpiler' LIMIT 10; Limit (cost=11583.61..11583.64 rows=10 width=32) (actual time=1431.591..1431.594 rows=10.00 loops=1) -> Sort (cost=11583.61..11804.76 rows=88459 width=32) (actual time=1431.589..1431.591 rows=10.00 loops=1) Sort Key: ((word <-> 'caterpiler'::text)) - Sort Method: top-N heapsort Memory: 25kB + Sort Method: top-N quickselect Memory: 25kB -> Foreign Scan on words (cost=0.00..9672.05 rows=88459 width=32) (actual time=0.057..1286.455 rows=479829.00 loops=1) Foreign File: /usr/share/dict/words Foreign File Size: 4953699 diff --git a/src/backend/optimizer/path/costsize.c b/src/backend/optimizer/path/costsize.c index f760ef9aa3a..12675a7cad6 100644 --- a/src/backend/optimizer/path/costsize.c +++ b/src/backend/optimizer/path/costsize.c @@ -1932,8 +1932,12 @@ cost_recursive_union(Path *runion, Path *nrterm, Path *rterm) * cpu = comparison_cost * t * log2(t) * * If the sort is bounded (i.e., only the first k result tuples are needed) - * and k tuples can fit into sort_mem, we use a heap method that keeps only - * k tuples in the heap; this will require about t*log2(k) tuple comparisons. + * and k tuples can fit into sort_mem, we keep a buffer of O(k) tuples and + * prune it back to k with quickselect whenever it fills. Each input tuple + * costs about one comparison to accept or reject, and the pruning adds a + * linear amount of work amortized across the input, so the whole selection + * runs in about t comparisons; a final sort of the k survivors adds + * k*log2(k). * * The disk traffic is assumed to be 3/4ths sequential and 1/4th random * accesses (XXX can't we refine that guess?) @@ -2015,12 +2019,16 @@ cost_tuplesort(Cost *startup_cost, Cost *run_cost, else if (tuples > 2 * output_tuples || input_bytes > sort_mem_bytes) { /* - * We'll use a bounded heap-sort keeping just K tuples in memory, for - * a total number of tuple comparisons of N log2 K; but the constant - * factor is a bit higher than for quicksort. Tweak it so that the - * cost curve is continuous at the crossover point. + * We'll use a bounded quickselect, keeping a buffer of O(K) tuples in + * memory. Every input tuple pays about one comparison to be accepted + * or rejected, and the prune passes add a linear amount of work + * amortized over the input; the K survivors are then sorted for a + * further K*log2(K) comparisons. This is strictly below the old + * heap estimate of N*log2(2K), which is correct: quickselect replaced + * the heap here precisely because it does less work. */ - *startup_cost = comparison_cost * tuples * LOG2(2.0 * output_tuples); + *startup_cost = comparison_cost * + (tuples + output_tuples * LOG2(2.0 * output_tuples)); } else { diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c index 31ce2e661e3..1925b0507e4 100644 --- a/src/backend/utils/sort/tuplesort.c +++ b/src/backend/utils/sort/tuplesort.c @@ -120,6 +120,24 @@ #define INITIAL_MEMTUPSIZE Max(1024, \ ALLOCSET_SEPARATE_THRESHOLD / sizeof(SortTuple) + 1) +/* + * Minimum buffer, in tuples, that a quickselect bounded sort keeps between + * prunes. A prune does O(buffer) work to discard (buffer - bound) tuples, so + * the amortized cost per input tuple is O(buffer / (buffer - bound)); it stays + * near O(1) only while the buffer is comfortably larger than bound. For a + * small bound, 2 * bound alone would prune after very few admissions and lose + * that amortization, so the buffer never drops below this floor. + * + * 1000 is chosen to fit inside the initial memtuples array (INITIAL_MEMTUPSIZE + * is at least 1024), so a small bound neither grows that array nor leaves it + * mostly idle. The exact value is not critical: a larger floor helps the + * admit-heavy case and never hurts the reject-heavy one, where almost every + * input loses the first comparison and is never buffered. + */ +#define TOPN_SELECT_MIN_BUFFER 1000 +StaticAssertDecl(TOPN_SELECT_MIN_BUFFER < INITIAL_MEMTUPSIZE, + "TOPN_SELECT_MIN_BUFFER must fit in the initial memtuples array"); + /* GUC variables */ bool trace_sort = false; @@ -155,6 +173,9 @@ typedef enum { TSS_INITIAL, /* Loading tuples; still within memory limit */ TSS_BOUNDED, /* Loading tuples into bounded-size heap */ + TSS_BOUNDED_SELECT, /* Loading tuples into a Max(2 * bound, 1000) + * buffer that quickselect prunes back to + * bound */ TSS_BUILDRUNS, /* Loading tuples; writing to tape */ TSS_SORTEDINMEM, /* Sort completed entirely in memory */ TSS_SORTEDONTAPE, /* Sort completed, final run is on tape */ @@ -189,6 +210,8 @@ struct Tuplesortstate bool bounded; /* did caller specify a maximum number of * tuples to return? */ bool boundUsed; /* true if we made use of a bounded heap */ + bool boundSelectUsed; /* true if we made use of bounded + * quickselect */ int bound; /* if bounded, the maximum number of tuples */ int64 tupleMem; /* memory consumed by individual tuples. * storing this separately from what we track @@ -460,6 +483,7 @@ static bool mergereadnext(Tuplesortstate *state, LogicalTape *srcTape, SortTuple static void dumptuples(Tuplesortstate *state, bool alltuples); static void make_bounded_heap(Tuplesortstate *state); static void sort_bounded_heap(Tuplesortstate *state); +static void prune_bounded_select(Tuplesortstate *state); static void tuplesort_sort_memtuples(Tuplesortstate *state); static void tuplesort_heap_insert(Tuplesortstate *state, SortTuple *tuple); static void tuplesort_heap_replace_top(Tuplesortstate *state, SortTuple *tuple); @@ -680,6 +704,7 @@ tuplesort_begin_batch(Tuplesortstate *state) state->status = TSS_INITIAL; state->bounded = false; state->boundUsed = false; + state->boundSelectUsed = false; state->availMem = state->allowedMem; @@ -780,7 +805,7 @@ tuplesort_set_bound(Tuplesortstate *state, int64 bound) bool tuplesort_used_bound(Tuplesortstate *state) { - return state->boundUsed; + return state->boundUsed || state->boundSelectUsed; } /* @@ -1149,6 +1174,22 @@ tuplesort_puttuple_common(Tuplesortstate *state, SortTuple *tuple, (state->memtupcount > state->bound * 2 || (state->memtupcount > state->bound && LACKMEM(state)))) { + /* + * If 2 * bound tuples fit in memory, keep a buffer of them and + * prune it back to bound with quickselect whenever it fills. + */ + if (state->bound > 0 && !LACKMEM(state)) + { + if (trace_sort) + elog(LOG, "switching to bounded quickselect at %d tuples: %s", + state->memtupcount, + pg_rusage_show(&state->ru_start)); + prune_bounded_select(state); + state->status = TSS_BOUNDED_SELECT; + MemoryContextSwitchTo(oldcontext); + return; + } + if (trace_sort) elog(LOG, "switching to bounded heapsort at %d tuples: %s", state->memtupcount, @@ -1202,6 +1243,37 @@ tuplesort_puttuple_common(Tuplesortstate *state, SortTuple *tuple, } break; + case TSS_BOUNDED_SELECT: + + /* + * memtuples[bound - 1] is the largest of the bound smallest + * tuples seen so far, so nothing >= it can make the cut. + */ + if (COMPARETUP(state, tuple, &state->memtuples[state->bound - 1]) >= 0) + { + free_sort_tuple(state, tuple); + CHECK_FOR_INTERRUPTS(); + break; + } + /* the buffer never outgrows the array; see TOPN_SELECT_MIN_BUFFER */ + Assert(state->memtupcount < state->memtupsize); + state->memtuples[state->memtupcount++] = *tuple; + + /* + * Prune when the buffer fills. The buffer is Max(2 * bound, + * TOPN_SELECT_MIN_BUFFER) tuples, except that once work_mem is + * full we prune at 2 * bound so the floor cannot push us further + * over. Either threshold leaves more than bound tuples to + * discard per prune, so each prune costs O(buffer) for O(buffer) + * tuples: O(1) amortized. Like the heap, a bounded sort may still + * exceed work_mem when later tuples are wider than earlier ones, + * since bound of them must be kept. + */ + if (state->memtupcount > Max(state->bound * 2, TOPN_SELECT_MIN_BUFFER) || + (LACKMEM(state) && state->memtupcount > state->bound * 2)) + prune_bounded_select(state); + break; + case TSS_BUILDRUNS: /* @@ -1331,6 +1403,18 @@ tuplesort_performsort(Tuplesortstate *state) state->markpos_eof = false; break; + case TSS_BOUNDED_SELECT: + if (state->memtupcount > state->bound) + prune_bounded_select(state); + tuplesort_sort_memtuples(state); + state->status = TSS_SORTEDINMEM; + state->boundSelectUsed = true; + state->current = 0; + state->eof_reached = false; + state->markpos_offset = 0; + state->markpos_eof = false; + break; + case TSS_BUILDRUNS: /* @@ -2426,7 +2510,9 @@ tuplesort_get_stats(Tuplesortstate *state, switch (state->maxSpaceStatus) { case TSS_SORTEDINMEM: - if (state->boundUsed) + if (state->boundSelectUsed) + stats->sortMethod = SORT_TYPE_TOP_N_QUICKSELECT; + else if (state->boundUsed) stats->sortMethod = SORT_TYPE_TOP_N_HEAPSORT; else stats->sortMethod = SORT_TYPE_QUICKSORT; @@ -2455,6 +2541,8 @@ tuplesort_method_name(TuplesortMethod m) return "still in progress"; case SORT_TYPE_TOP_N_HEAPSORT: return "top-N heapsort"; + case SORT_TYPE_TOP_N_QUICKSELECT: + return "top-N quickselect"; case SORT_TYPE_QUICKSORT: return "quicksort"; case SORT_TYPE_EXTERNAL_SORT: @@ -2574,6 +2662,125 @@ sort_bounded_heap(Tuplesortstate *state) state->boundUsed = true; } +/* + * Return the index of the median of memtuples[i], [j] and [k]. + * + * This mirrors ST_MED3 in sort_template.h, but returns an index rather than a + * pointer so the caller can swap by position, and compares through COMPARETUP + * rather than an inlined comparator. + */ +static inline int +med3_index(Tuplesortstate *state, int i, int j, int k) +{ + SortTuple *a = state->memtuples; + + return COMPARETUP(state, &a[i], &a[j]) < 0 ? + (COMPARETUP(state, &a[j], &a[k]) < 0 ? j : + (COMPARETUP(state, &a[i], &a[k]) < 0 ? k : i)) : + (COMPARETUP(state, &a[j], &a[k]) > 0 ? j : + (COMPARETUP(state, &a[i], &a[k]) < 0 ? i : k)); +} + +/* + * Rearrange memtuples[0 .. n-1] so that memtuples[k] holds the tuple it would + * hold if the array were sorted, with nothing larger before it and nothing + * smaller after it. + * + * Hoare partitioning stops on keys equal to the pivot, so runs of equal keys + * still split evenly. + */ +static void +tuplesort_select(Tuplesortstate *state, int n, int k) +{ + SortTuple *a = state->memtuples; + int lo = 0; + int hi = n - 1; + + Assert(k >= 0 && k < n); + + while (hi > lo) + { + int len = hi - lo + 1; + int mid = lo + len / 2; + int p; + int i; + int j; + SortTuple tmp; + + CHECK_FOR_INTERRUPTS(); + + /* median of three, or pseudo-median of nine for larger ranges */ + if (len > 40) + { + int d = len / 8; + + p = med3_index(state, + med3_index(state, lo, lo + d, lo + 2 * d), + med3_index(state, mid - d, mid, mid + d), + med3_index(state, hi - 2 * d, hi - d, hi)); + } + else + p = med3_index(state, lo, mid, hi); + + tmp = a[lo]; + a[lo] = a[p]; + a[p] = tmp; + + i = lo; + j = hi + 1; + for (;;) + { + while (COMPARETUP(state, &a[++i], &a[lo]) < 0) + if (i == hi) + break; + while (COMPARETUP(state, &a[lo], &a[--j]) < 0) + if (j == lo) + break; + if (i >= j) + break; + tmp = a[i]; + a[i] = a[j]; + a[j] = tmp; + } + tmp = a[lo]; + a[lo] = a[j]; + a[j] = tmp; + + /* a[lo .. j-1] <= a[j] <= a[j+1 .. hi] */ + if (j == k) + return; + if (j > k) + hi = j - 1; + else + lo = j + 1; + } +} + +/* + * Keep only the bound smallest memtuples, leaving the largest of them at + * memtuples[bound - 1]. + */ +static void +prune_bounded_select(Tuplesortstate *state) +{ + Assert(state->bounded); + Assert(state->memtupcount > state->bound); + Assert(SERIAL(state)); + + /* + * Partition so memtuples[bound - 1] is the bound'th smallest, with the + * bound smallest tuples before it. We do not re-scan the array to assert + * the partition here: a prune runs on the hot path, many times per sort, + * and tuplesort_sort_memtuples() already calls verify_memtuples_sorted() + * on the final output under assertions. + */ + tuplesort_select(state, state->memtupcount, state->bound - 1); + + for (int i = state->bound; i < state->memtupcount; i++) + free_sort_tuple(state, &state->memtuples[i]); + state->memtupcount = state->bound; +} + /* radix sort routines */ diff --git a/src/include/executor/instrument_node.h b/src/include/executor/instrument_node.h index c48e8ad756e..6e6cb71f58e 100644 --- a/src/include/executor/instrument_node.h +++ b/src/include/executor/instrument_node.h @@ -241,8 +241,9 @@ typedef enum SORT_TYPE_QUICKSORT = 1 << 1, SORT_TYPE_EXTERNAL_SORT = 1 << 2, SORT_TYPE_EXTERNAL_MERGE = 1 << 3, + SORT_TYPE_TOP_N_QUICKSELECT = 1 << 4, } TuplesortMethod; -#define NUM_TUPLESORTMETHODS 4 +#define NUM_TUPLESORTMETHODS 5 typedef struct TuplesortInstrumentation { diff --git a/src/test/regress/expected/incremental_sort.out b/src/test/regress/expected/incremental_sort.out index ccad1cbcc31..41ec48a4223 100644 --- a/src/test/regress/expected/incremental_sort.out +++ b/src/test/regress/expected/incremental_sort.out @@ -520,13 +520,13 @@ select * from (select * from t order by a) s order by a, b limit 55; -- Test EXPLAIN ANALYZE with only a fullsort group. select explain_analyze_without_memory('select * from (select * from t order by a) s order by a, b limit 55'); - explain_analyze_without_memory ---------------------------------------------------------------------------------------------------------------- + explain_analyze_without_memory +------------------------------------------------------------------------------------------------------------------ Limit (actual rows=55.00 loops=1) -> Incremental Sort (actual rows=55.00 loops=1) Sort Key: t.a, t.b Presorted Key: t.a - Full-sort Groups: 2 Sort Methods: top-N heapsort, quicksort Average Memory: NNkB Peak Memory: NNkB + Full-sort Groups: 2 Sort Methods: quicksort, top-N quickselect Average Memory: NNkB Peak Memory: NNkB -> Sort (actual rows=101.00 loops=1) Sort Key: t.a Sort Method: quicksort Memory: NNkB @@ -554,8 +554,8 @@ select jsonb_pretty(explain_analyze_inc_sort_nodes_without_memory('select * from "Full-sort Groups": { + "Group Count": 2, + "Sort Methods Used": [ + - "top-N heapsort", + - "quicksort" + + "quicksort", + + "top-N quickselect" + ], + "Sort Space Memory": { + "Peak Sort Space Used": "NN", + @@ -761,14 +761,14 @@ order by v.n; -- Test EXPLAIN ANALYZE with both fullsort and presorted groups. select explain_analyze_without_memory('select * from (select * from t order by a) s order by a, b limit 70'); - explain_analyze_without_memory ----------------------------------------------------------------------------------------------------------------- + explain_analyze_without_memory +------------------------------------------------------------------------------------------------------------------- Limit (actual rows=70.00 loops=1) -> Incremental Sort (actual rows=70.00 loops=1) Sort Key: t.a, t.b Presorted Key: t.a Full-sort Groups: 1 Sort Method: quicksort Average Memory: NNkB Peak Memory: NNkB - Pre-sorted Groups: 5 Sort Methods: top-N heapsort, quicksort Average Memory: NNkB Peak Memory: NNkB + Pre-sorted Groups: 5 Sort Methods: quicksort, top-N quickselect Average Memory: NNkB Peak Memory: NNkB -> Sort (actual rows=1000.00 loops=1) Sort Key: t.a Sort Method: quicksort Memory: NNkB @@ -806,8 +806,8 @@ select jsonb_pretty(explain_analyze_inc_sort_nodes_without_memory('select * from "Pre-sorted Groups": { + "Group Count": 5, + "Sort Methods Used": [ + - "top-N heapsort", + - "quicksort" + + "quicksort", + + "top-N quickselect" + ], + "Sort Space Memory": { + "Peak Sort Space Used": "NN", + diff --git a/src/test/regress/expected/subselect.out b/src/test/regress/expected/subselect.out index ef73218d9db..3fca6d86b71 100644 --- a/src/test/regress/expected/subselect.out +++ b/src/test/regress/expected/subselect.out @@ -2396,7 +2396,7 @@ select * from explain_sq_limit(); -> Subquery Scan on x (actual rows=3.00 loops=1) -> Sort (actual rows=3.00 loops=1) Sort Key: sq_limit.c1, sq_limit.pk - Sort Method: top-N heapsort Memory: xxx + Sort Method: top-N quickselect Memory: xxx -> Seq Scan on sq_limit (actual rows=8.00 loops=1) (6 rows) diff --git a/src/test/regress/expected/tuplesort.out b/src/test/regress/expected/tuplesort.out index fc1321bf443..da3f0dda81f 100644 --- a/src/test/regress/expected/tuplesort.out +++ b/src/test/regress/expected/tuplesort.out @@ -703,3 +703,95 @@ EXPLAIN (COSTS OFF) :qry; (10 rows) COMMIT; +---- +-- Bounded sorts. Once 2 * bound tuples are in memory, the sort keeps a +-- buffer of them (at least TOPN_SELECT_MIN_BUFFER, 1000) and prunes it to +-- bound with quickselect. Compare each with a full sort, which is what a +-- bound above INT_MAX / 2 gets. +---- +CREATE TEMP TABLE bounded_sort AS + SELECT g AS id, (g * 7919) % 1000 AS k, md5(g::text) AS t + FROM generate_series(1, 5000) g; +-- true if ORDER BY ... LIMIT returns the same rows, in the same order, as a +-- full sort cut to the same length +CREATE FUNCTION bounded_sort_ok(ord text, lim int) RETURNS bool +LANGUAGE plpgsql AS $$ +DECLARE + bounded int[]; + full_sort int[]; +BEGIN + EXECUTE format('SELECT array(SELECT id FROM bounded_sort ORDER BY %s LIMIT %s)', + ord, lim) INTO bounded; + EXECUTE format('SELECT array(SELECT id FROM (SELECT id FROM bounded_sort ORDER BY %s LIMIT 1073741824) f LIMIT %s)', + ord, lim) INTO full_sort; + RETURN bounded = full_sort; +END $$; +SELECT o, l +FROM unnest(ARRAY['k, id', 'k DESC, id', 't', 't DESC', 'id DESC']) o, + unnest(ARRAY[1, 2, 7, 100, 499, 500, 501, 1250, 2499, 2500]) l +WHERE NOT bounded_sort_ok(o, l); + o | l +---+--- +(0 rows) + +-- duplicates: the bound falls inside a run of equal keys +SELECT count(*), count(DISTINCT k), min(k), max(k) +FROM (SELECT k FROM bounded_sort ORDER BY k LIMIT 2000) s; + count | count | min | max +-------+-------+-----+----- + 2000 | 400 | 0 | 399 +(1 row) + +-- rescan with a different bound each time +SELECT l, max(s.k), count(*) +FROM generate_series(10, 50, 20) l, + LATERAL (SELECT k FROM bounded_sort ORDER BY k, id LIMIT l) s +GROUP BY l ORDER BY l; + l | max | count +----+-----+------- + 10 | 1 | 10 + 30 | 5 | 30 + 50 | 9 | 50 +(3 rows) + +-- work_mem runs out after the buffer starts: narrow rows with large keys +-- come first, then wide rows that sort before them, so the survivors get +-- wider until bound of them no longer fit in work_mem and the sort prunes +-- early, at 2 * bound, for the rest of the input +CREATE TEMP TABLE bounded_sort_wide AS + SELECT g AS id, + CASE WHEN g > 3000 THEN g - 3000 ELSE 100000 + g END AS k, + CASE WHEN g > 3000 THEN repeat(md5(g::text), 16) ELSE 'x' END AS pad + FROM generate_series(1, 6000) g; +BEGIN; +SET LOCAL work_mem = '256kB'; +SELECT array(SELECT id FROM (SELECT id, pad FROM bounded_sort_wide + ORDER BY k, id LIMIT 400) s) = + array(SELECT id FROM (SELECT id FROM bounded_sort_wide + ORDER BY k, id LIMIT 1073741824) f LIMIT 400) AS ok; + ok +---- + t +(1 row) + +COMMIT; +-- Parallel ORDER BY ... LIMIT. The bound reaches only the leader's sort (a +-- parallel worker sorts without a bound and the leader merges), so the +-- quickselect path, which asserts it runs serially, must still produce the +-- right answer when the plan goes parallel. +BEGIN; +SET LOCAL min_parallel_table_scan_size = 0; +SET LOCAL parallel_setup_cost = 0; +SET LOCAL parallel_tuple_cost = 0; +SET LOCAL max_parallel_workers_per_gather = 2; +SELECT array(SELECT id FROM (SELECT id FROM bounded_sort + ORDER BY k, id LIMIT 2000) s) = + array(SELECT id FROM (SELECT id FROM bounded_sort + ORDER BY k, id LIMIT 1073741824) f LIMIT 2000) AS ok; + ok +---- + t +(1 row) + +COMMIT; +DROP FUNCTION bounded_sort_ok(text, int); diff --git a/src/test/regress/sql/tuplesort.sql b/src/test/regress/sql/tuplesort.sql index 8476e594e6c..563cbc025d0 100644 --- a/src/test/regress/sql/tuplesort.sql +++ b/src/test/regress/sql/tuplesort.sql @@ -305,3 +305,77 @@ EXPLAIN (COSTS OFF) :qry; :qry; COMMIT; + +---- +-- Bounded sorts. Once 2 * bound tuples are in memory, the sort keeps a +-- buffer of them (at least TOPN_SELECT_MIN_BUFFER, 1000) and prunes it to +-- bound with quickselect. Compare each with a full sort, which is what a +-- bound above INT_MAX / 2 gets. +---- +CREATE TEMP TABLE bounded_sort AS + SELECT g AS id, (g * 7919) % 1000 AS k, md5(g::text) AS t + FROM generate_series(1, 5000) g; + +-- true if ORDER BY ... LIMIT returns the same rows, in the same order, as a +-- full sort cut to the same length +CREATE FUNCTION bounded_sort_ok(ord text, lim int) RETURNS bool +LANGUAGE plpgsql AS $$ +DECLARE + bounded int[]; + full_sort int[]; +BEGIN + EXECUTE format('SELECT array(SELECT id FROM bounded_sort ORDER BY %s LIMIT %s)', + ord, lim) INTO bounded; + EXECUTE format('SELECT array(SELECT id FROM (SELECT id FROM bounded_sort ORDER BY %s LIMIT 1073741824) f LIMIT %s)', + ord, lim) INTO full_sort; + RETURN bounded = full_sort; +END $$; + +SELECT o, l +FROM unnest(ARRAY['k, id', 'k DESC, id', 't', 't DESC', 'id DESC']) o, + unnest(ARRAY[1, 2, 7, 100, 499, 500, 501, 1250, 2499, 2500]) l +WHERE NOT bounded_sort_ok(o, l); + +-- duplicates: the bound falls inside a run of equal keys +SELECT count(*), count(DISTINCT k), min(k), max(k) +FROM (SELECT k FROM bounded_sort ORDER BY k LIMIT 2000) s; + +-- rescan with a different bound each time +SELECT l, max(s.k), count(*) +FROM generate_series(10, 50, 20) l, + LATERAL (SELECT k FROM bounded_sort ORDER BY k, id LIMIT l) s +GROUP BY l ORDER BY l; + +-- work_mem runs out after the buffer starts: narrow rows with large keys +-- come first, then wide rows that sort before them, so the survivors get +-- wider until bound of them no longer fit in work_mem and the sort prunes +-- early, at 2 * bound, for the rest of the input +CREATE TEMP TABLE bounded_sort_wide AS + SELECT g AS id, + CASE WHEN g > 3000 THEN g - 3000 ELSE 100000 + g END AS k, + CASE WHEN g > 3000 THEN repeat(md5(g::text), 16) ELSE 'x' END AS pad + FROM generate_series(1, 6000) g; +BEGIN; +SET LOCAL work_mem = '256kB'; +SELECT array(SELECT id FROM (SELECT id, pad FROM bounded_sort_wide + ORDER BY k, id LIMIT 400) s) = + array(SELECT id FROM (SELECT id FROM bounded_sort_wide + ORDER BY k, id LIMIT 1073741824) f LIMIT 400) AS ok; +COMMIT; + +-- Parallel ORDER BY ... LIMIT. The bound reaches only the leader's sort (a +-- parallel worker sorts without a bound and the leader merges), so the +-- quickselect path, which asserts it runs serially, must still produce the +-- right answer when the plan goes parallel. +BEGIN; +SET LOCAL min_parallel_table_scan_size = 0; +SET LOCAL parallel_setup_cost = 0; +SET LOCAL parallel_tuple_cost = 0; +SET LOCAL max_parallel_workers_per_gather = 2; +SELECT array(SELECT id FROM (SELECT id FROM bounded_sort + ORDER BY k, id LIMIT 2000) s) = + array(SELECT id FROM (SELECT id FROM bounded_sort + ORDER BY k, id LIMIT 1073741824) f LIMIT 2000) AS ok; +COMMIT; + +DROP FUNCTION bounded_sort_ok(text, int); base-commit: 5878a42580898b9a57e28f52e346026a74a20821 -- 2.54.0