From 02ae61a8a3bed641c0b8cea58282aed452c401da Mon Sep 17 00:00:00 2001 From: Chengpeng Yan Date: Tue, 28 Jul 2026 17:46:21 +0800 Subject: [PATCH v1] Delay abbreviation shutdown for bounded sorts A bound is only a hint until tuplesort switches to a bounded heap. Keep abbreviated keys for ordinary sorts with an unused bound, and restore full keys only when making that switch. --- src/backend/utils/sort/tuplesort.c | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c index c0e7527b9ca..6e770f41dfe 100644 --- a/src/backend/utils/sort/tuplesort.c +++ b/src/backend/utils/sort/tuplesort.c @@ -759,19 +759,6 @@ tuplesort_set_bound(Tuplesortstate *state, int64 bound) state->bounded = true; state->bound = (int) bound; - - /* - * Bounded sorts are not an effective target for abbreviated key - * optimization. Disable by setting state to be consistent with no - * abbreviation support. - */ - state->base.sortKeys->abbrev_converter = NULL; - if (state->base.sortKeys->abbrev_full_comparator) - state->base.sortKeys->comparator = state->base.sortKeys->abbrev_full_comparator; - - /* Not strictly necessary, but be tidy */ - state->base.sortKeys->abbrev_abort = NULL; - state->base.sortKeys->abbrev_full_comparator = NULL; } /* @@ -2483,6 +2470,7 @@ tuplesort_space_type_name(TuplesortSpaceType t) static void make_bounded_heap(Tuplesortstate *state) { + SortSupport sortKey = state->base.sortKeys; int tupcount = state->memtupcount; int i; @@ -2491,6 +2479,16 @@ make_bounded_heap(Tuplesortstate *state) Assert(tupcount >= state->bound); Assert(SERIAL(state)); + if (sortKey->abbrev_converter != NULL) + { + /* Restore keys before switching to the authoritative comparator. */ + REMOVEABBREV(state, state->memtuples, state->memtupcount); + sortKey->comparator = sortKey->abbrev_full_comparator; + sortKey->abbrev_converter = NULL; + sortKey->abbrev_abort = NULL; + sortKey->abbrev_full_comparator = NULL; + } + /* Reverse sort direction so largest entry will be at root */ reversedirection(state); -- 2.50.1 (Apple Git-155)