| From: | zengxx <xiangxin_zeng(at)qq(dot)com> |
|---|---|
| To: | pgsql-hackers <pgsql-hackers(at)lists(dot)postgresql(dot)org> |
| Subject: | [PATCH 0/1] Put presorted aggregate sort keys first in Aggregate |
| Date: | 2026-11-26 13:33:27 |
| Message-ID: | tencent_836CCA9F256944221059E97D779AC62AE709@qq.com |
| Views: | Whole Thread | Raw Message | Download mbox | Resend email |
| Thread: | |
| Lists: | pgsql-hackers |
Hi,
Here is a small planner-only patch that speeds up ordered aggregates
under GROUP BY when the aggregate's argument is varlena, for example
SELECT g, string_agg(v, ',' ORDER BY k) FROM t GROUP BY g;
Problem
-------
With enable_presorted_aggregate, the input of this query is sorted once
by (g, k), and the Aggregate node reads it in that order.
make_group_input_target() emits the grouping columns first and then the
Vars used by the aggregates in expression-tree order, so the Sort gets
(g, v, k): the argument column is ahead of the key column.
tuplesort stores only the first sort key in SortTuple.datum1. The other
sort keys are fetched from the tuple with heap_getattr during every
comparison that ties on the earlier keys. Locating k means stepping
over v first. For a varlena v that is a read of its length header each
time, because offsets after the first variable-width column are not
cached. With few groups, a large share of the comparisons tie on g and
pay that price.
The patch
---------
make_group_input_target() now puts the Vars used in the sort keys of
presorted aggregates right after the grouping columns, ahead of the
remaining Vars, so the Sort gets (g, k, v). make_window_input_target()
does something similar for window PARTITION BY / ORDER BY keys.
Only aggregates that are actually presorted are considered. The others
sort their own input inside the Aggregate node, on tuples built from
their own argument list, so moving their keys in the input buys nothing;
and a varlena key of an aggregate that was not chosen would otherwise
end up in front of the real sort keys. Nothing is done in two cases, so
those plans stay as they are: when no aggregate sort key was appended to
the grouping keys, or when there is a single sort key, which tuplesort
fetches once per tuple wherever it is.
Benchmark
---------
PostgreSQL master 5fbff0e089 without and with the patch; Linux x86-64 on
a laptop (Intel Core i5-12500H, 8 CPUs, 5.8 GB RAM, WSL2); release
builds; one pgbench client.
Setup, once on an empty database of each build:
CREATE TABLE t AS
SELECT k % 10 AS g,
k,
k % 3 AS k2,
(k * 1.5)::text AS v,
k % 1000000 AS vi,
'g' || (k % 10) AS gt
FROM generate_series(1, 2000000) AS k;
ANALYZE t;
Query files, one per row of the table, in that order. Each holds these
three lines
SET work_mem = '512MB';
SET jit = off;
SET max_parallel_workers_per_gather = 0;
and one SELECT:
SELECT g, string_agg(v, ',' ORDER BY k) FROM t GROUP BY g;
SELECT g, string_agg(vi::text, ',' ORDER BY k) FROM t GROUP BY g;
SELECT g, string_agg(v, ',' ORDER BY k2, k) FROM t GROUP BY g;
SELECT g, string_agg(v, ',' ORDER BY k),
string_agg(vi::text, ';' ORDER BY k) FROM t GROUP BY g;
SELECT g, string_agg(v, ',' ORDER BY k),
string_agg(vi::text, ';' ORDER BY k2, k) FROM t GROUP BY g;
SELECT gt, string_agg(v, ',' ORDER BY k) FROM t GROUP BY gt;
Timing on both builds, for each query file: pgbench -n -f <file> -t 10.
Each build runs each file 6 times, base first in odd rounds and
patched first in even rounds. The table gives the median of the
"latency average" values of each file, in ms; "ratio" is base divided by
patched.
case before after ratio
---------------------------------------------------------------
varlena argument: ORDER BY k 1465 1090 1.35
fixed-width argument: ORDER BY k 1028 1022 1.01
varlena argument: ORDER BY k2, k 2575 1631 1.58
two aggregates, same sort key 1640 1282 1.28
two aggregates, different sort keys 2511 2122 1.18
varlena grouping column: GROUP BY gt 2128 2054 1.04
The table has six columns and every query uses a few of them, so on both
builds the scan's target list differs from the physical column order and
the scan projects. The numbers show the sort alone.
The first row is the query above. The second shows that a fixed-width
argument has nothing to gain. The third has two sort keys, and both sat
behind the argument column; with three values in k2, about every third
comparison that ties on g ties on k2 as well. The fourth and the fifth
have two ordered aggregates: the Sort is shared when they order by the
same key; when they do not, only one of them is presorted and the other
sorts its own input inside the Aggregate node. The sixth has a varlena
grouping column: the sort key then sits behind it in both builds, and
the patch cannot help.
Plan changes
------------
Besides the column order, a query that benefits may see two changes:
- One more projection (Result or Subquery Scan) when its input is a
non-partitioned appendrel or a subquery, because those do not
regenerate their paths for the new target. Whether a Subquery Scan is
needed can also flip the other way, depending on the column order the
subquery is written in.
- The estimated cost grows by cpu_tuple_cost per row for that
projection, which can tip a close serial/parallel choice towards a
parallel plan.
I found no query whose results change (see "Testing").
Testing
-------
- 26 EXPLAIN (VERBOSE, COSTS OFF) cases added to aggregates.sql pin the
column order; five of the queries are run as well. make check passes
in the C and C.UTF-8 locales (243 tests).
- 440 queries aimed at this code (ordered and DISTINCT aggregates with
GROUP BY, over joins, subqueries, CTEs, partitioned and inherited
tables, grouping sets, window functions and parallel plans) were
compared between the patched and the unpatched build: 407 give
identical results, 3 are rejected identically on both sides, 30 are
compared by plan only.
- A second corpus of 14,259 query-setting pairs (11 planner settings)
was run against an --enable-cassert build of the patched tree: no
assertion failure, no crash. Of its results, 190 pairs (27 queries)
differ from the unpatched build, all explained by the order of
elements that tie on an aggregate's sort key (161 pairs) or by
synchronize_seqscans in aggregates without ORDER BY (29 pairs).
Not addressed
-------------
- Expression sort keys (ORDER BY k + 1). The column the Sort compares
is one that createplan.c appends at the end of the target list, so it
stays behind the argument columns, whatever happens to the Vars inside
the expression.
- A MergeAppend directly below the aggregation. Its child sorts keep
the old layout.
- An argument that is itself the first sort key and is varlena, as in
string_agg(txt, ',' ORDER BY txt, k). The column order is the same as
before.
Make sense?
--
Xiangxin Zeng
| Attachment | Content-Type | Size |
|---|---|---|
| 0001-Put-presorted-aggregate-sort-keys-first-in-Aggregate.patch | application/octet-stream | 38.8 KB |
| From | Date | Subject | |
|---|---|---|---|
| Next Message | Daniel Gustafsson | 2026-11-26 13:55:21 | Re: Fix a wrong comment in UpdateDeadTupleRetentionStatus() |
| Previous Message | Osama Abdul Qader | 2026-11-26 13:31:45 | Re: Fix deparsing of SUBSTRING SIMILAR with an operator as first argument |