pg.ddx.io  pgsql-hackers@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: ChenhuiMo <chenhuimo.mch@qq.com>
To: pgsql-hackers <pgsql-hackers@postgresql.org>
Subject: [RFC PATCH] Cost-based delayed projection for ORDER BY ... LIMIT
Date: Fri, 4 Sep 2026 11:48:49 +0800
Message-ID: <tencent_077318C5D9B6ADE9E99A42255C6ACC77DB06@qq.com> (raw)

Hi,

While testing a query of the following form, I noticed that several individually cheap target expressions were evaluated for every input row, even though only one row survived the top-N sort:

SELECT a,
       a / (a * -1),
       a::numeric AS b,
       abs(a::numeric) / 12345.345632
FROM t
ORDER BY a
LIMIT 1;

With one million rows, rewriting it manually so that the non-sort expressions are evaluated after the top-N operation:

SELECT s.a,
       s.a / (s.a * -1),
       s.a::numeric AS b,
       abs(s.a::numeric) / 12345.345632
FROM (
    SELECT a
    FROM t
    ORDER BY a
    LIMIT 1
) AS s
ORDER BY s.a;

made a large difference. On my first test system, current master took about 95 ms for the original query, while the manually delayed version took about 15 ms.

I looked at make_sort_input_target() and found that PostgreSQL already postpones an expression when its individual cost is greater than:

10 * cpu_operator_cost

and a LIMIT or tuple fraction makes postponing useful. However, this does not consider a target list containing several expressions that are cheap individually but expensive in aggregate.

For a top-N query, I think there are three relevant factors:

the total per-tuple cost of postponable target expressions;
the estimated number of input rows;
the number of rows that need to survive the Sort, including OFFSET.

The attached POC therefore also postpones individually cheap expressions when:

total_expression_cost * (input_rows - limit_tuples)
    >
10 * cpu_operator_cost * limit_tuples

This roughly compares the expression work avoided on discarded rows with a conservative threshold proportional to the rows that survive the Sort.

The factor of 10 is retained from the existing per-expression heuristic. I do not intend to claim that it is the best factor; this is one of the parts on which I would particularly appreciate feedback.

For parallel plans, simply postponing the target expressions was not enough, because apply_projection_to_path() could push the projection below Gather or Gather Merge. The POC keeps projections selected by the new rule on the non-partial path, so that they are evaluated by the leader rather than independently for each worker's top-N candidates.

I wrote a small benchmark extension to compare the three query forms, verify their results, and record the automatic plan shape. It compares three strategies:

auto

The normal query, allowing the planner to choose the projection position.

manual-late

A subquery that performs ORDER BY/LIMIT before evaluating the target expressions, with the required ordering also specified by the outer query.

forced-early

A query that adds the deterministic projected expressions as secondary sort keys. This forces them below Sort while preserving the same serial or parallel Sort/Gather Merge topology. The benchmark data uses a unique leading key, and the added expressions are deterministic functions of that key.

Before timing, the benchmark uses EXCEPT ALL in both directions to verify that the three strategies return equivalent multisets. It then runs them in rotating order to reduce cache-order bias and reports the minimum execution time from repeated runs. The test matrix varies LIMIT selectivity, the number of expressions, the declared per-expression cost, and whether parallel query is enabled.

Here are selected results from an Intel Core i5-13500H system with 32 GB LPDDR5. Times are executor times in milliseconds reported by EXPLAIN ANALYZE with TIMING disabled.

case                                  master auto  patched auto  speedup
serial, 4 x COST 1, LIMIT 1               103.189        33.299    3.10x
serial, 4 x COST 1, LIMIT 1%              107.690        36.228    2.97x
serial, 4 x COST 1, LIMIT 10%             180.063        67.149    2.68x
serial, 4 x COST 1, LIMIT 25%             184.370        80.680    2.29x
serial, 8 x COST 1, LIMIT 10%             244.155        86.155    2.83x
serial, 16 x COST 1, LIMIT 10%            358.287        74.293    4.82x
parallel, 4 x COST 1, LIMIT 1              45.060        15.700    2.87x
parallel, 4 x COST 1, LIMIT 1%             49.642        19.240    2.58x
numeric example above                      95.162        17.142    5.55x

The speedup column is master auto time divided by patched auto time.

For the numeric example, the three strategies behaved as follows:

                 auto  manual-late  forced-early
master         95.162       15.294        96.118
patched        17.142       17.130       108.338

In this case, master auto was close to forced-early, while patched auto was close to manual-late.

I also repeated the patched benchmark on a second system, an Intel Core i9-12900H with 64 GB DDR5. The absolute times were different, but the relative results were similar:

case                                   first system   second system
serial, 4 x COST 1, LIMIT 1                   3.07x           2.72x
serial, 4 x COST 1, LIMIT 1%                  2.90x           3.02x
serial, 4 x COST 1, LIMIT 25%                 2.32x           2.30x
serial, 4 x COST 1, LIMIT 50%                 1.97x           1.91x
parallel, 4 x COST 1, LIMIT 1                 2.91x           2.59x
parallel, 4 x COST 1, LIMIT 25%               1.29x           1.24x
numeric example                               6.32x           6.89x

These values are forced-early time divided by manual-late time.

The POC is deliberately conservative and still chooses early projection in some cases where manual-late happens to be faster in this benchmark. For example, four COST 1 expressions with a 50% LIMIT remain early. The actual CPU work performed by the synthetic functions is only approximately related to their declared procost, so I do not think these cases alone establish a better threshold.

I am mainly interested in feedback on the approach:

Is aggregate target expression cost the right quantity to consider?
Is comparing avoided expression work on discarded rows against work on surviving rows a reasonable model?
Are current_rel->rows and root->limit_tuples appropriate estimates at this point in grouping_planner()?
Should a projection selected this way stay above Gather/Gather Merge, or are there cases where evaluating it in workers would be preferable?
Should this eventually be represented as competing paths and decided by ordinary path costing instead of another heuristic in make_sort_input_target()?
Is retaining the existing factor of 10 a reasonable conservative starting point?

The attached patch is intended as a POC for design discussion, not yet as a commit-ready patch. I have also attached the benchmark extension; selected results from the tested builds are included above.

I have not registered this in a CommitFest, since I would first like to get feedback on the costing and parallel-placement approach.

Thanks,
ChenHui Mo

Attachments:

0001-Consider-aggregate-target-cost-for-top-N-sorts.patch (application/octet-stream, 7.5K) download From 3808d4ed9ed6bf9799b4840e788a84957e971b12 Mon Sep 17 00:00:00 2001 From: sohardforaname <organic_chemistry@foxmail.com> Date: Thu, 3 Sep 2026 23:24:31 +0800 Subject: [PATCH] Consider aggregate target cost for top-N sorts make_sort_input_target() postpones an expensive target expression based on its individual cost. This misses target lists containing multiple expressions that are individually cheap but expensive in aggregate. Estimate the expression work avoided for rows discarded by ORDER BY LIMIT, and postpone costful expressions when that exceeds a conservative threshold. Keep projections postponed this way above Gather and Gather Merge so that they are evaluated after the global top-N operation. --- src/backend/optimizer/plan/planner.c | 70 ++++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 3 deletions(-) diff --git a/src/backend/optimizer/plan/planner.c b/src/backend/optimizer/plan/planner.c index c3c158a253d..6864f714929 100644 --- a/src/backend/optimizer/plan/planner.c +++ b/src/backend/optimizer/plan/planner.c @@ -225,6 +225,7 @@ static RelOptInfo *create_ordered_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, + bool postpone_projection_in_leader, double limit_tuples); static PathTarget *make_group_input_target(PlannerInfo *root, PathTarget *final_target); @@ -243,6 +244,8 @@ static List *make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, List *tlist); static PathTarget *make_sort_input_target(PlannerInfo *root, PathTarget *final_target, + double input_rows, + bool *postpone_projection_in_leader, bool *have_postponed_srfs); static void adjust_paths_for_srfs(PlannerInfo *root, RelOptInfo *rel, List *targets, List *targets_contain_srfs); @@ -1696,6 +1699,7 @@ grouping_planner(PlannerInfo *root, double tuple_fraction, int64 offset_est = 0; int64 count_est = 0; double limit_tuples = -1.0; + bool postpone_projection_in_leader = false; bool have_postponed_srfs = false; PathTarget *final_target; List *final_targets; @@ -1933,6 +1937,8 @@ grouping_planner(PlannerInfo *root, double tuple_fraction, { sort_input_target = make_sort_input_target(root, final_target, + current_rel->rows, + &postpone_projection_in_leader, &have_postponed_srfs); sort_input_target_parallel_safe = is_parallel_safe(root, (Node *) sort_input_target->exprs); @@ -2111,6 +2117,7 @@ grouping_planner(PlannerInfo *root, double tuple_fraction, current_rel, final_target, final_target_parallel_safe, + postpone_projection_in_leader, have_postponed_srfs ? -1.0 : limit_tuples); /* Fix things up if final_target contains SRFs */ @@ -5560,6 +5567,7 @@ create_ordered_paths(PlannerInfo *root, RelOptInfo *input_rel, PathTarget *target, bool target_parallel_safe, + bool postpone_projection_in_leader, double limit_tuples) { Path *cheapest_input_path = input_rel->cheapest_total_path; @@ -5638,8 +5646,17 @@ create_ordered_paths(PlannerInfo *root, * the target to be applied, a projection step is needed. */ if (!equal(sorted_path->pathtarget->exprs, target->exprs)) - sorted_path = apply_projection_to_path(root, ordered_rel, + { + if (postpone_projection_in_leader && + (IsA(sorted_path, GatherPath) || + IsA(sorted_path, GatherMergePath))) + sorted_path = (Path *) + create_projection_path(root, ordered_rel, + sorted_path, target); + else + sorted_path = apply_projection_to_path(root, ordered_rel, sorted_path, target); + } add_path(ordered_rel, sorted_path); } @@ -5719,8 +5736,15 @@ create_ordered_paths(PlannerInfo *root, * from the target to be applied, a projection step is needed. */ if (!equal(sorted_path->pathtarget->exprs, target->exprs)) - sorted_path = apply_projection_to_path(root, ordered_rel, + { + if (postpone_projection_in_leader) + sorted_path = (Path *) + create_projection_path(root, ordered_rel, + sorted_path, target); + else + sorted_path = apply_projection_to_path(root, ordered_rel, sorted_path, target); + } add_path(ordered_rel, sorted_path); } @@ -6647,6 +6671,9 @@ make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, * computed earlier. * * 'final_target' is the query's final target list (in PathTarget form) + * 'input_rows' is the estimated number of rows before the Sort step + * 'postpone_projection_in_leader' is set if a Top-N cost decision postponed + * expressions that should not be pushed below a Gather or Gather Merge * 'have_postponed_srfs' is an output argument, see below * * The result is the PathTarget to be computed by the plan node immediately @@ -6659,6 +6686,8 @@ make_pathkeys_for_window(PlannerInfo *root, WindowClause *wc, static PathTarget * make_sort_input_target(PlannerInfo *root, PathTarget *final_target, + double input_rows, + bool *postpone_projection_in_leader, bool *have_postponed_srfs) { Query *parse = root->parse; @@ -6666,6 +6695,8 @@ make_sort_input_target(PlannerInfo *root, int ncols; bool *col_is_srf; bool *postpone_col; + Cost *col_cost; + Cost postponable_cost = 0; bool have_srf; bool have_volatile; bool have_expensive; @@ -6679,12 +6710,14 @@ make_sort_input_target(PlannerInfo *root, /* Shouldn't get here unless query has ORDER BY */ Assert(parse->sortClause); - *have_postponed_srfs = false; /* default result */ + *postpone_projection_in_leader = false; + *have_postponed_srfs = false; /* default results */ /* Inspect tlist and collect per-column information */ ncols = list_length(final_target->exprs); col_is_srf = palloc0_array(bool, ncols); postpone_col = palloc0_array(bool, ncols); + col_cost = palloc0_array(Cost, ncols); have_srf = have_volatile = have_expensive = have_srf_sortcols = false; i = 0; @@ -6729,6 +6762,8 @@ make_sort_input_target(PlannerInfo *root, QualCost cost; cost_qual_eval_node(&cost, (Node *) expr, root); + col_cost[i] = cost.per_tuple; + postponable_cost += cost.per_tuple; /* * We arbitrarily define "expensive" as "more than 10X @@ -6754,6 +6789,35 @@ make_sort_input_target(PlannerInfo *root, i++; } + /* + * The fixed per-expression threshold above misses target lists made up of + * several individually cheap expressions when a small LIMIT means that + * very few input rows survive the Sort. In that case, compare the cost + * avoided on discarded rows with a conservative per-output-row threshold. + * + * root->limit_tuples is positive only when LIMIT/OFFSET could be + * estimated and can safely be applied to the scan/join result. Keep the + * historical factor of 10, but scale it by the number of rows expected to + * survive rather than applying it independently to every input row. + */ + if (root->limit_tuples > 0 && + input_rows > root->limit_tuples && + postponable_cost * (input_rows - root->limit_tuples) > + 10 * cpu_operator_cost * root->limit_tuples) + { + i = 0; + foreach(lc, final_target->exprs) + { + /* Zero means a Var, Const, or another cost-free expression. */ + if (col_cost[i] > 0) + postpone_col[i] = true; + i++; + } + + have_expensive = true; + *postpone_projection_in_leader = true; + } + /* * We can postpone SRFs if we have some but none are in sortgroupref cols. */ -- 2.43.0
benchmark.sql (application/octet-stream, 1.3K) download Makefile (application/octet-stream, 168B) download README.md (application/octet-stream, 3.1K) download topnbench.c (application/octet-stream, 19.4K) download topnbench.control (application/octet-stream, 153B) download topnbench--1.0.sql (application/octet-stream, 2.2K) download

view thread (2+ messages)  latest in thread

Message-ID: <tencent_077318C5D9B6ADE9E99A42255C6ACC77DB06@qq.com>
Permalink:  ../tencent_077318C5D9B6ADE9E99A42255C6ACC77DB06@qq.com/
Also on:    postgresql.org/message-id/tencent_077318C5D9B6ADE9E99A42255C6ACC77DB06@qq.com

 ·  · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-hackers@postgresql.org
  Cc: chenhuimo.mch@qq.com
  Subject: Re: [RFC PATCH] Cost-based delayed projection for ORDER BY ... LIMIT
  In-Reply-To: <tencent_077318C5D9B6ADE9E99A42255C6ACC77DB06@qq.com>
  References: <tencent_077318C5D9B6ADE9E99A42255C6ACC77DB06@qq.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox