postgres.git / summary / log / commit / refs

commit    f9c88051d64670847cf678b44ecba590dbbc3cca
Author:   David Rowley <drowley@postgresql.org>
Date:     Wed Nov 18 01:13:56 2026 +0000

    Fix possible crash with Incremental Sort when boundedness changes
    
    ExecSetTupleBound() can adjust the IncrementalSortState bounded flag
    between rescans of the Incremental Sort node.  Starting with 6ed83d5fa,
    tuplesort.c uses the Bump memory context type when bounded sorts are not
    required, as we never need to pfree individual tuples when not
    performing a bounded sort.  If the initial tuplesort was created without
    TUPLESORT_ALLOWBOUNDED, and a subsequent scan became bounded, then
    tuplesort would mistakenly store the tuples in a Bump context, but
    bounded sorts pfree() tuples, which Bump does not support as it does not
    use chunk headers.
    
    This can happen when a LIMIT node's tuple limit isn't a Const, as the
    actual limit may be known for some scans but not others.  If the LIMIT
    isn't known for the first scan, then the tuplesorts will be initialized
    without the TUPLESORT_ALLOWBOUNDED flag, and if a later scan obtains a
    bound, then the tuplesort will mistakenly use a Bump context type.
    
    Here we fix this by adding a new external function for tuplesort which
    allows the TUPLESORT_ALLOWBOUNDED flag to be changed.  This must be
    changed before calling tuplesort_reset() as that's the point when
    tuplesort_begin_batch() creates the tuplecontext as either an AllocSet
    context or Bump context.  Ideally tuplesort_reset() would grow an extra
    boolean parameter to control this on reset, but we can't change the
    signature of that function in the backbranches.
    
    Versions prior to v17 didn't have 6ed83d5fa or Bump memory contexts.
    Non-bounded sorts use Generation contexts in v15 and v16, which do
    support pfree().  This change is still required there to fix an Assert
    failure in tuplesort_set_bound() and to resolve inefficient memory
    usage as the Generation context is not well suited for pfreeing chunks
    in an arbitrary order.  AllocSet is better suited as it can reuse pfree'd
    memory.
    
    Reported-by: shihao zhong <zhong950419@gmail.com>
    Author: David Rowley <dgrowleyml@gmail.com>
    Tested-by: shihao zhong <zhong950419@gmail.com>
    Discussion: https://postgr.es/m/CAGRkXqRXMiR9EBxBT7VEF0jF_9NJAxVcGrtRdsTZOfNkHfVtsg@mail.gmail.com
    Backpatch-through: 15


src/backend/executor/nodeIncrementalSort.c | 10 ++++++- src/backend/utils/sort/tuplesort.c | 16 +++++++++++ src/include/utils/tuplesort.h | 2 ++ src/test/regress/expected/incremental_sort.out | 37 ++++++++++++++++++++++++++ src/test/regress/sql/incremental_sort.sql | 19 +++++++++++++ 5 files changed, 83 insertions(+), 1 deletion(-) diff --git a/src/backend/executor/nodeIncrementalSort.c b/src/backend/executor/nodeIncrementalSort.c index 235fb90564a..7f0cbf79aa1 100644 --- a/src/backend/executor/nodeIncrementalSort.c +++ b/src/backend/executor/nodeIncrementalSort.c @@ -1143,12 +1143,20 @@ ExecReScanIncrementalSort(IncrementalSortState *node) * repay the setup cost, and because ExecIncrementalSort guards presorted * column functions by checking to see if the full sort state has been * initialized yet, setting the sort states to null here might actually - * cause a leak. + * cause a leak. The IncrementalSortState's bounded flag may change + * between scans, per ExecSetTupleBound(), so we must toggle that flag in + * the sort options before calling tuplesort_reset(). */ if (node->fullsort_state != NULL) + { + tuplesort_set_allowbounded(node->fullsort_state, node->bounded); tuplesort_reset(node->fullsort_state); + } if (node->prefixsort_state != NULL) + { + tuplesort_set_allowbounded(node->prefixsort_state, node->bounded); tuplesort_reset(node->prefixsort_state); + } /* * If chgParam of subnode is not null, then the plan will be re-scanned by diff --git a/src/backend/utils/sort/tuplesort.c b/src/backend/utils/sort/tuplesort.c index 7c4d6dc106b..a99c013321e 100644 --- a/src/backend/utils/sort/tuplesort.c +++ b/src/backend/utils/sort/tuplesort.c @@ -893,6 +893,22 @@ tuplesort_used_bound(Tuplesortstate *state) return state->boundUsed; } +/* + * tuplesort_set_allowbounded + * Set or unset TUPLESORT_ALLOWBOUNDED sort flag on an existing state. + * + * NOTE: tuplesort_reset() must be called after this function for the changes + * to take effect. + */ +void +tuplesort_set_allowbounded(Tuplesortstate *state, bool allowbounded) +{ + if (allowbounded) + state->base.sortopt |= TUPLESORT_ALLOWBOUNDED; + else + state->base.sortopt &= ~TUPLESORT_ALLOWBOUNDED; +} + /* * tuplesort_free * diff --git a/src/include/utils/tuplesort.h b/src/include/utils/tuplesort.h index cde83f62015..0790a6b5ff3 100644 --- a/src/include/utils/tuplesort.h +++ b/src/include/utils/tuplesort.h @@ -384,6 +384,8 @@ extern bool tuplesort_gettuple_common(Tuplesortstate *state, bool forward, SortTuple *stup); extern bool tuplesort_skiptuples(Tuplesortstate *state, int64 ntuples, bool forward); +extern void tuplesort_set_allowbounded(Tuplesortstate *state, + bool allowbounded); extern void tuplesort_end(Tuplesortstate *state); extern void tuplesort_reset(Tuplesortstate *state); diff --git a/src/test/regress/expected/incremental_sort.out b/src/test/regress/expected/incremental_sort.out index 5fd54a10b1a..a8a5f6d4fb6 100644 --- a/src/test/regress/expected/incremental_sort.out +++ b/src/test/regress/expected/incremental_sort.out @@ -720,6 +720,43 @@ select * from t left join (select * from (select * from t order by a) v order by (2 rows) rollback; +-- try rescan with a LIMIT node where some scans receive a LIMIT NULL and +-- others receive a LIMIT <n>. +-- Ensure we get an Incremental Sort plan +explain (costs off) +select v.n, count(*) from (values (null::int), (3), (null::int)) v(n), +lateral (select unique1 from tenk1 where hundred < 2 + order by hundred, unique1 limit v.n) s +group by v.n +order by v.n; + QUERY PLAN +----------------------------------------------------------------------- + GroupAggregate + Group Key: "*VALUES*".column1 + -> Sort + Sort Key: "*VALUES*".column1 + -> Nested Loop + -> Values Scan on "*VALUES*" + -> Limit + -> Incremental Sort + Sort Key: tenk1.hundred, tenk1.unique1 + Presorted Key: tenk1.hundred + -> Index Scan using tenk1_hundred on tenk1 + Index Cond: (hundred < 2) +(12 rows) + +-- Check we get the correct results from that plan +select v.n, count(*) from (values (null::int), (3), (null::int)) v(n), +lateral (select unique1 from tenk1 where hundred < 2 + order by hundred, unique1 limit v.n) s +group by v.n +order by v.n; + n | count +---+------- + 3 | 3 + | 400 +(2 rows) + -- 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 diff --git a/src/test/regress/sql/incremental_sort.sql b/src/test/regress/sql/incremental_sort.sql index ab471bdfffc..1121aeca9eb 100644 --- a/src/test/regress/sql/incremental_sort.sql +++ b/src/test/regress/sql/incremental_sort.sql @@ -162,6 +162,25 @@ set local enable_sort = off; explain (costs off) select * from t left join (select * from (select * from t order by a) v order by a, b) s on s.a = t.a where t.a in (1, 2); select * from t left join (select * from (select * from t order by a) v order by a, b) s on s.a = t.a where t.a in (1, 2); rollback; + +-- try rescan with a LIMIT node where some scans receive a LIMIT NULL and +-- others receive a LIMIT <n>. + +-- Ensure we get an Incremental Sort plan +explain (costs off) +select v.n, count(*) from (values (null::int), (3), (null::int)) v(n), +lateral (select unique1 from tenk1 where hundred < 2 + order by hundred, unique1 limit v.n) s +group by v.n +order by v.n; + +-- Check we get the correct results from that plan +select v.n, count(*) from (values (null::int), (3), (null::int)) v(n), +lateral (select unique1 from tenk1 where hundred < 2 + order by hundred, unique1 limit v.n) s +group by v.n +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'); select jsonb_pretty(explain_analyze_inc_sort_nodes_without_memory('select * from (select * from t order by a) s order by a, b limit 70')); [parent: 999b85bbb551]