Re: Unfortunate pushing down of expressions below sort

From: Chengpeng Yan <chengpeng_yan(at)outlook(dot)com>
To: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
Cc: Andres Freund <andres(at)anarazel(dot)de>, PostgreSQL-development <pgsql-hackers(at)postgresql(dot)org>, David Rowley <dgrowleyml(at)gmail(dot)com>
Subject: Re: Unfortunate pushing down of expressions below sort
Date: 2026-12-05 14:30:49
Message-ID: A7E490C6-7AC9-4DE9-AD51-C5828A47FD53@outlook.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi Tom,

> On Apr 8, 2026, at 04:16, Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us> wrote:
>
> Chengpeng Yan <chengpeng_yan(at)Outlook(dot)com> writes:
>> Following up on the discussion below, I now have a patch.
>
>> The patch extends make_sort_input_target() with a conservative rule:
>> defer additional non-sort targetlist expressions past Sort only when
>> doing so does not require carrying any additional Vars/PlaceHolderVars
>> through Sort. This way, Sort input width never increases.
>
> I spent some time thinking about this.
>
> One thing I think we need to keep in mind is that if we don't postpone
> an expression past Sort, and the user doesn't like that, she can
> easily rewrite the query to force it; as indeed Andres demonstrated
> at the start of this thread. But overriding an unwanted planner
> decision to postpone is harder. I think you can do it with
>
> SELECT * FROM (SELECT x,y,f(z) FROM ... OFFSET 0) ORDER BY whatever;
>
> but if you forget the OFFSET-0 optimization fence you may find
> f(z) getting evaluated after the sort anyway. And the fence might
> foreclose some other optimization you did want.
>
> Also, make_sort_input_target() has gone basically unchanged since
> 2016, without that many complaints. So I think we need to be pretty
> conservative about adding postponement choices that aren't forced by
> semantic requirements.
>
> The rule stated above seems pretty conservative, but either it's not
> conservative enough or you didn't implement it right, because the
> regression test changes show the v2 patch is very willing to create
> Result nodes where there were none before, even when there's no LIMIT
> and thus no reason to think we can save any expression evaluations.
> That extra plan node has nonzero cost that I don't think you're
> accounting for. It'll still be a win if enough data volume is removed
> from the Sort step, but I don't see any consideration of how much
> we're actually saving before deciding to add the projection step.
>
> So I think we need some sort of gating rule, whereby we only postpone
> these expressions if (a) there was already a reason to add a
> projection or (b) we can make some cost-based or at least heuristic
> estimate that says we'll cut the sort data volume significantly.
> Maybe (b) needs to interact with the existing heuristic about
> postponing expensive expressions, not sure.
>
> Independently of that, I don't especially like the changes in
> make_sort_input_target(). They seem rather inelegant and expensive
> (and underdocumented), as well as duplicative of other work already
> being done in the function. It may be time to tackle the unfinished
> work mentioned in the existing comments about avoiding redundant
> cost/width calculations ...
>
> regards, tom lane

Thanks for the detailed review, and sorry for the late follow-up.

You're right about v2. Its rule kept the sort input from getting wider,
but said nothing about whether a projection step was worth adding, so it
added Result nodes to plans that had none. The code was also
special-cased and hard to extend. I also agree with your point that an
unwanted postponement is much harder for users to undo than a missing
one, so postponement that isn't required for correctness has to be
conservative.

v3 is split into two patches.

0001 restructures make_sort_input_target() with no plan changes: it now
decides what to postpone before building the sort input target, so a new
rule fits in one place. It also takes on part of the redundant
cost/width calculations mentioned in the existing comments, reusing the
per-column costs computed to detect expensive expressions when costing
the new target, which removes one of the two XXX comments. Removing the
other would mean keeping per-column costs in PathTarget, a much wider
change whose savings I'm not sure would justify it. If reusing costs
within make_sort_input_target() doesn't seem worth it either, I can drop
it, which makes 0001 simpler and leaves costsize.c untouched.

0002 implements your gate (a): if make_sort_input_target() is already
adding a post-sort projection and there is a LIMIT, it also postpones
plain tlist columns whose inputs already pass through the Sort. It
never adds a projection step or a sort column. From the new test:

select unique1, unique2 + nextval('testseq'), unique2 * 2,
tenthous * 2, stringu1 || 'x'
from tenk1 order by tenthous limit 10;

nextval() already forces a projection. unique2 passes through the Sort
anyway for the postponed unique2 + nextval(), and tenthous is the sort
key, so unique2 * 2 and tenthous * 2 are now computed after the Sort,
for the 10 returned rows only. stringu1 || 'x' stays below the Sort,
since postponing it would add stringu1 to the sorted tuples.

For follow-ups:

For (b), as you suggested, it could be either cost-based or heuristic.
For the cost-based way, create_ordered_paths() could generate both
alternatives, computing the expressions before or after the Sort, and
let add_path() keep the cheaper one. But that could be a large change,
and I'm not sure the current cost model can compare the two well
enough. The heuristic way could build on the existing rule for
expensive expressions, as you mentioned. That would be much simpler
to implement, though the rule itself needs some thought. Gate (a) is
more clear-cut, since it never adds a plan node, which is why I started
with it.

Andres's suggestion of letting Sort project could cover more cases: it
would make it cheap to postpone expressions past the Sort even when no
post-sort projection is needed today, so more queries could benefit. But
it is more complex and touches a wider area, so it needs more thought.

Do 0001 and 0002 look reasonable as a first step? Both follow-ups will
need more investigation before I can draw any conclusions.

--
Best regards,
Chengpeng Yan

Attachment Content-Type Size
v3-0001-Refactor-make_sort_input_target-to-separate-phase.patch application/octet-stream 9.8 KB
v3-0002-Postpone-more-sort-outputs-when-a-projection-is-n.patch application/octet-stream 6.2 KB

In response to

Browse pgsql-hackers by date

  From Date Subject
Next Message shihao zhong 2026-12-05 15:33:32 Re: VACUUM FULL / REPACK on the primary make hot standby queries miss rows (2012 report, still unfixed)
Previous Message Kirill Reshke 2026-12-05 13:24:38 Re: Convert ALL SubLinks to ANY SubLinks