Re: [PATCH] Consider window functions when reordering GROUP BY items
Re: [PATCH] Consider window functions when reordering GROUP BY items
От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Zhenglong,
Thanks for the patch. I applied v1 on master and looked at the
plan shapes. The queries below return the same results as master.
The patch matches the GROUP BY items against the window's keys
from the front, and stops at the first key whose sort direction
is not the same as well. But the two sides get their directions
from different ORDER BY clauses. So when the window's ORDER BY
has a descending key, matching stops at that key, unless the
ORDER BY outside the window gives that column the same direction.
GROUP BY and PARTITION BY do not need any particular sort direction;
they only bring equal values together. So when the same column also
appears in an ORDER BY, they simply take its direction: GROUP BY
from the ORDER BY outside the window, PARTITION BY from the window's
ORDER BY. Either way, one sort is enough even with DESC.
There is no such relation between GROUP BY and the window's
ORDER BY, though. Could the patch let the GROUP BY items take the
direction of the window's ORDER BY when it matches them against the
window's keys, so that the DESC case would also need only one sort?
CREATE TABLE t (a int, b int, c int);
INSERT INTO t SELECT i % 100, i % 10, i % 1000
FROM generate_series(1, 100000) i;
ANALYZE t;
SET enable_hashagg = off;
When the window's ORDER BY is ascending, the
patch works as described; two sorts become one:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c)
FROM t GROUP BY a, b, c;
-- master
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Sort
Sort Key: b, c
-> Group
Group Key: a, b, c
-> Sort
Sort Key: a, b, c
-> Seq Scan on t
-- patched
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Group
Group Key: b, c, a
-> Sort
Sort Key: b, c, a
-> Seq Scan on t
But if only c is changed to c DESC, the patch matches b and
stops at c, and the window still needs an incremental sort:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c;
-- master
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Sort
Sort Key: b, c DESC
-> Group
Group Key: a, b, c
-> Sort
Sort Key: a, b, c
-> Seq Scan on t
-- patched
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Incremental Sort
Sort Key: b, c DESC
Presorted Key: b
-> Group
Group Key: b, a, c
-> Sort
Sort Key: b, a, c
-> Seq Scan on t
If ORDER BY b, c DESC is added outside the window
to the same query, the GROUP BY item c takes that
DESC, and even master does it with one sort:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c ORDER BY b, c DESC;
-- master and patched
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Group
Group Key: b, c, a
-> Sort
Sort Key: b, c DESC, a
-> Seq Scan on t
That grouping sort, b, c DESC, a, is exactly the order
the window needs. It would be nice if the patch could
pick it without the ORDER BY outside the window.
Please also consider the case where the ORDER BY outside
the window has a different direction from the window's.
With c DESC in the window and b, c outside, both master
and the patch do one full sort and two incremental sorts:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c ORDER BY b, c;
-- patched (master differs only in grouping on b, c, a)
Incremental Sort
Sort Key: b, c
Presorted Key: b
-> WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Incremental Sort
Sort Key: b, c DESC
Presorted Key: b
-> Group
Group Key: b, a, c
-> Sort
Sort Key: b, a, c
-> Seq Scan on t
Right now the plan sorts c ascending for the grouping,
descending for the window, and ascending again for the
ORDER BY outside the window. If the grouping sort followed the
window's sort, one of the incremental sorts would go away.
One thing to watch out for when implementing this: in this
query the GROUP BY item c has already taken the ascending
direction from the ORDER BY outside the window. So this cannot
be solved by looking only at the relation between the window's
ORDER BY and GROUP BY; the relations with the ORDER BY outside
the window and with PARTITION BY have to be taken into account
as well. Also, if the ORDER BY outside the window brought in a
different equality operator (ORDER BY ... USING), that changes
what counts as a group, so the GROUP BY item should follow the
window's direction only when the equality operator is the same.
Best regards,
Henson
Thanks for the patch. I applied v1 on master and looked at the
plan shapes. The queries below return the same results as master.
The patch matches the GROUP BY items against the window's keys
from the front, and stops at the first key whose sort direction
is not the same as well. But the two sides get their directions
from different ORDER BY clauses. So when the window's ORDER BY
has a descending key, matching stops at that key, unless the
ORDER BY outside the window gives that column the same direction.
GROUP BY and PARTITION BY do not need any particular sort direction;
they only bring equal values together. So when the same column also
appears in an ORDER BY, they simply take its direction: GROUP BY
from the ORDER BY outside the window, PARTITION BY from the window's
ORDER BY. Either way, one sort is enough even with DESC.
There is no such relation between GROUP BY and the window's
ORDER BY, though. Could the patch let the GROUP BY items take the
direction of the window's ORDER BY when it matches them against the
window's keys, so that the DESC case would also need only one sort?
CREATE TABLE t (a int, b int, c int);
INSERT INTO t SELECT i % 100, i % 10, i % 1000
FROM generate_series(1, 100000) i;
ANALYZE t;
SET enable_hashagg = off;
When the window's ORDER BY is ascending, the
patch works as described; two sorts become one:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c)
FROM t GROUP BY a, b, c;
-- master
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Sort
Sort Key: b, c
-> Group
Group Key: a, b, c
-> Sort
Sort Key: a, b, c
-> Seq Scan on t
-- patched
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Group
Group Key: b, c, a
-> Sort
Sort Key: b, c, a
-> Seq Scan on t
But if only c is changed to c DESC, the patch matches b and
stops at c, and the window still needs an incremental sort:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c;
-- master
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Sort
Sort Key: b, c DESC
-> Group
Group Key: a, b, c
-> Sort
Sort Key: a, b, c
-> Seq Scan on t
-- patched
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Incremental Sort
Sort Key: b, c DESC
Presorted Key: b
-> Group
Group Key: b, a, c
-> Sort
Sort Key: b, a, c
-> Seq Scan on t
If ORDER BY b, c DESC is added outside the window
to the same query, the GROUP BY item c takes that
DESC, and even master does it with one sort:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c ORDER BY b, c DESC;
-- master and patched
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Group
Group Key: b, c, a
-> Sort
Sort Key: b, c DESC, a
-> Seq Scan on t
That grouping sort, b, c DESC, a, is exactly the order
the window needs. It would be nice if the patch could
pick it without the ORDER BY outside the window.
Please also consider the case where the ORDER BY outside
the window has a different direction from the window's.
With c DESC in the window and b, c outside, both master
and the patch do one full sort and two incremental sorts:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c ORDER BY b, c;
-- patched (master differs only in grouping on b, c, a)
Incremental Sort
Sort Key: b, c
Presorted Key: b
-> WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Incremental Sort
Sort Key: b, c DESC
Presorted Key: b
-> Group
Group Key: b, a, c
-> Sort
Sort Key: b, a, c
-> Seq Scan on t
Right now the plan sorts c ascending for the grouping,
descending for the window, and ascending again for the
ORDER BY outside the window. If the grouping sort followed the
window's sort, one of the incremental sorts would go away.
One thing to watch out for when implementing this: in this
query the GROUP BY item c has already taken the ascending
direction from the ORDER BY outside the window. So this cannot
be solved by looking only at the relation between the window's
ORDER BY and GROUP BY; the relations with the ORDER BY outside
the window and with PARTITION BY have to be taken into account
as well. Also, if the ORDER BY outside the window brought in a
different equality operator (ORDER BY ... USING), that changes
what counts as a group, so the GROUP BY item should follow the
window's direction only when the equality operator is the same.
Best regards,
Henson
Re: [PATCH] Consider window functions when reordering GROUP BY items
Hi Henson,
Thanks for the careful review and the test cases.
> Could the patch let the GROUP BY items take the direction of the
> window's ORDER BY when it matches them against the window's keys,
> so that the DESC case would also need only one sort?
Yes. v2 is attached. preprocess_groupclause() now matches a GROUP BY
item to a sort clause when both refer to the same targetlist entry and
use the same equality operator, and the GROUP BY item then takes on the
sort operator and NULLS ordering of that clause. A copy is made, so the
parse tree is left untouched. With that, your queries become:
-- c DESC in the window, no ORDER BY outside
WindowAgg
-> Group
Group Key: b, c, a
-> Sort
Sort Key: b, c DESC, a
-> Seq Scan on t
-- c DESC in the window, ORDER BY b, c outside
Incremental Sort
Sort Key: b, c
Presorted Key: b
-> WindowAgg
-> Group
Group Key: b, c, a
-> Sort
Sort Key: b, c DESC, a
-> Seq Scan on t
so the second case loses one of its two incremental sorts.
> One thing to watch out for when implementing this: in this query the
> GROUP BY item c has already taken the ascending direction from the
> ORDER BY outside the window.
Right. The relaxed matching applies to the whole list being matched
(the first window's PARTITION BY, its ORDER BY, then the query's ORDER
BY), so it doesn't matter where the GROUP BY item or the PARTITION BY
item got its direction from. One consequence is that the list can now
refer to the same column more than once, e.g. c DESC from the window
and c from the ORDER BY outside it. A later reference with the same
equality operator is redundant, so it's skipped. This affects queries
without window functions too, e.g. "ORDER BY x USING ~<~, x, y", where
the items after the second x can now be matched as well.
> Also, if the ORDER BY outside the window brought in a different
> equality operator (ORDER BY ... USING), that changes what counts as
> a group, so the GROUP BY item should follow the window's direction
> only when the equality operator is the same.
Agreed, and that is what v2 does: when the equality operators differ,
matching stops as before. There's a test for this using record's *<,
whose equality operator *= differs from the default =. v2 also requires
the sort operator to come from the same btree operator family as the
GROUP BY item's own, so only the direction and NULLS ordering can
change. A family sharing the equality operator isn't enough, since its
ordering need not agree with that operator; see the text_pattern_ops
case at the end.
While testing this I found a regression. Once the GROUP BY keys follow
the window's direction, an input path sorted in the original direction
can no longer be used for grouping. With an index on (b, c):
SELECT b, c, count(*), count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY b, c;
master groups straight off the index and then sorts only the groups for
the window. With the change alone, the planner instead sorted the whole
input by b, c DESC before grouping, which was about 3x slower on 2M rows.
The cause is older than this patch. group_keys_reorder_by_pathkeys(),
and the GROUP BY check in truncate_useless_pathkeys(), match the input
pathkeys to the GROUP BY pathkeys by pointer, so the sort direction has
to agree too. Master already shows the same problem without any window
functions:
CREATE INDEX ON t (b, c);
SELECT b, c, count(*) FROM t GROUP BY b, c ORDER BY b, c DESC;
This sorts all of the input by b, c DESC incrementally, when it could
group off the index and then sort only the groups.
So the series is now:
0001 lets group_keys_reorder_by_pathkeys() match an input pathkey with
the same equivalence class and operator family regardless of
direction, adjusting a copy of the GROUP BY clause to agree with
it, and makes truncate_useless_pathkeys() keep such pathkeys. In
the query above, on 2M rows, the estimated cost goes from 280732
to 52878 and the run time from 333 ms to 98 ms. Aggregate
pathkeys are still matched exactly, as an aggregate's ORDER BY
does depend on direction. No existing regression test output
changes.
0002 is the window patch with the change you suggested, rebased on
0001. The index case above again groups off the index.
For testing, beyond the regression tests, I compared results between
sorted and hashed grouping on a few tens of thousands of randomly
generated queries. They covered GROUP BY, one to three windows with
random directions, NULLS ordering, USING and COLLATE, and optional
ORDER BY, LIMIT, HAVING and DISTINCT. I also ran targeted cases with
partitionwise and eager aggregation, parallel plans, prepared
statements with generic plans, and grouping sets. No result differences
or assertion failures turned up.
Unrelated to this patch, but noticed along the way: for text_pattern_ops
under a nondeterministic collation, "=" is collation-aware whereas ~<~
compares bytes, so the two disagree on which values are equal. Since the
parser copies ~<~ into the GROUP BY item, sorted grouping on master
already returns wrong results:
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2',
deterministic = false);
CREATE TABLE ct (x text COLLATE ci);
INSERT INTO ct VALUES ('a'), ('B'), ('A'), ('b'), ('a');
SET enable_hashagg = off;
SELECT x, count(*) FROM ct GROUP BY x ORDER BY x USING ~<~;
This returns four groups (A, B, a, b) instead of two (a, b), because 'A'
and 'a' are not adjacent in ~<~ order; hashed grouping gets it right.
An earlier version of v2 let the GROUP BY item adopt ~<~ from a
window's ORDER BY as well, which is why v2 now stays within the same
operator family, and there's a test for that in collate.icu.utf8. I'll
start a separate thread for the issue on master.
Best regards,
Zhenglong
Thanks for the careful review and the test cases.
> Could the patch let the GROUP BY items take the direction of the
> window's ORDER BY when it matches them against the window's keys,
> so that the DESC case would also need only one sort?
Yes. v2 is attached. preprocess_groupclause() now matches a GROUP BY
item to a sort clause when both refer to the same targetlist entry and
use the same equality operator, and the GROUP BY item then takes on the
sort operator and NULLS ordering of that clause. A copy is made, so the
parse tree is left untouched. With that, your queries become:
-- c DESC in the window, no ORDER BY outside
WindowAgg
-> Group
Group Key: b, c, a
-> Sort
Sort Key: b, c DESC, a
-> Seq Scan on t
-- c DESC in the window, ORDER BY b, c outside
Incremental Sort
Sort Key: b, c
Presorted Key: b
-> WindowAgg
-> Group
Group Key: b, c, a
-> Sort
Sort Key: b, c DESC, a
-> Seq Scan on t
so the second case loses one of its two incremental sorts.
> One thing to watch out for when implementing this: in this query the
> GROUP BY item c has already taken the ascending direction from the
> ORDER BY outside the window.
Right. The relaxed matching applies to the whole list being matched
(the first window's PARTITION BY, its ORDER BY, then the query's ORDER
BY), so it doesn't matter where the GROUP BY item or the PARTITION BY
item got its direction from. One consequence is that the list can now
refer to the same column more than once, e.g. c DESC from the window
and c from the ORDER BY outside it. A later reference with the same
equality operator is redundant, so it's skipped. This affects queries
without window functions too, e.g. "ORDER BY x USING ~<~, x, y", where
the items after the second x can now be matched as well.
> Also, if the ORDER BY outside the window brought in a different
> equality operator (ORDER BY ... USING), that changes what counts as
> a group, so the GROUP BY item should follow the window's direction
> only when the equality operator is the same.
Agreed, and that is what v2 does: when the equality operators differ,
matching stops as before. There's a test for this using record's *<,
whose equality operator *= differs from the default =. v2 also requires
the sort operator to come from the same btree operator family as the
GROUP BY item's own, so only the direction and NULLS ordering can
change. A family sharing the equality operator isn't enough, since its
ordering need not agree with that operator; see the text_pattern_ops
case at the end.
While testing this I found a regression. Once the GROUP BY keys follow
the window's direction, an input path sorted in the original direction
can no longer be used for grouping. With an index on (b, c):
SELECT b, c, count(*), count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY b, c;
master groups straight off the index and then sorts only the groups for
the window. With the change alone, the planner instead sorted the whole
input by b, c DESC before grouping, which was about 3x slower on 2M rows.
The cause is older than this patch. group_keys_reorder_by_pathkeys(),
and the GROUP BY check in truncate_useless_pathkeys(), match the input
pathkeys to the GROUP BY pathkeys by pointer, so the sort direction has
to agree too. Master already shows the same problem without any window
functions:
CREATE INDEX ON t (b, c);
SELECT b, c, count(*) FROM t GROUP BY b, c ORDER BY b, c DESC;
This sorts all of the input by b, c DESC incrementally, when it could
group off the index and then sort only the groups.
So the series is now:
0001 lets group_keys_reorder_by_pathkeys() match an input pathkey with
the same equivalence class and operator family regardless of
direction, adjusting a copy of the GROUP BY clause to agree with
it, and makes truncate_useless_pathkeys() keep such pathkeys. In
the query above, on 2M rows, the estimated cost goes from 280732
to 52878 and the run time from 333 ms to 98 ms. Aggregate
pathkeys are still matched exactly, as an aggregate's ORDER BY
does depend on direction. No existing regression test output
changes.
0002 is the window patch with the change you suggested, rebased on
0001. The index case above again groups off the index.
For testing, beyond the regression tests, I compared results between
sorted and hashed grouping on a few tens of thousands of randomly
generated queries. They covered GROUP BY, one to three windows with
random directions, NULLS ordering, USING and COLLATE, and optional
ORDER BY, LIMIT, HAVING and DISTINCT. I also ran targeted cases with
partitionwise and eager aggregation, parallel plans, prepared
statements with generic plans, and grouping sets. No result differences
or assertion failures turned up.
Unrelated to this patch, but noticed along the way: for text_pattern_ops
under a nondeterministic collation, "=" is collation-aware whereas ~<~
compares bytes, so the two disagree on which values are equal. Since the
parser copies ~<~ into the GROUP BY item, sorted grouping on master
already returns wrong results:
CREATE COLLATION ci (provider = icu, locale = 'und-u-ks-level2',
deterministic = false);
CREATE TABLE ct (x text COLLATE ci);
INSERT INTO ct VALUES ('a'), ('B'), ('A'), ('b'), ('a');
SET enable_hashagg = off;
SELECT x, count(*) FROM ct GROUP BY x ORDER BY x USING ~<~;
This returns four groups (A, B, a, b) instead of two (a, b), because 'A'
and 'a' are not adjacent in ~<~ order; hashed grouping gets it right.
An earlier version of v2 let the GROUP BY item adopt ~<~ from a
window's ORDER BY as well, which is why v2 now stays within the same
operator family, and there's a test for that in collate.icu.utf8. I'll
start a separate thread for the issue on master.
Best regards,
Zhenglong
Henson Choi <assam258@gmail.com> 于2026年10月27日周二 15:11写道:
Hi Zhenglong,
Thanks for the patch. I applied v1 on master and looked at the
plan shapes. The queries below return the same results as master.
The patch matches the GROUP BY items against the window's keys
from the front, and stops at the first key whose sort direction
is not the same as well. But the two sides get their directions
from different ORDER BY clauses. So when the window's ORDER BY
has a descending key, matching stops at that key, unless the
ORDER BY outside the window gives that column the same direction.
GROUP BY and PARTITION BY do not need any particular sort direction;
they only bring equal values together. So when the same column also
appears in an ORDER BY, they simply take its direction: GROUP BY
from the ORDER BY outside the window, PARTITION BY from the window's
ORDER BY. Either way, one sort is enough even with DESC.
There is no such relation between GROUP BY and the window's
ORDER BY, though. Could the patch let the GROUP BY items take the
direction of the window's ORDER BY when it matches them against the
window's keys, so that the DESC case would also need only one sort?
CREATE TABLE t (a int, b int, c int);
INSERT INTO t SELECT i % 100, i % 10, i % 1000
FROM generate_series(1, 100000) i;
ANALYZE t;
SET enable_hashagg = off;
When the window's ORDER BY is ascending, the
patch works as described; two sorts become one:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c)
FROM t GROUP BY a, b, c;
-- master
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Sort
Sort Key: b, c
-> Group
Group Key: a, b, c
-> Sort
Sort Key: a, b, c
-> Seq Scan on t
-- patched
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Group
Group Key: b, c, a
-> Sort
Sort Key: b, c, a
-> Seq Scan on t
But if only c is changed to c DESC, the patch matches b and
stops at c, and the window still needs an incremental sort:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c;
-- master
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Sort
Sort Key: b, c DESC
-> Group
Group Key: a, b, c
-> Sort
Sort Key: a, b, c
-> Seq Scan on t
-- patched
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Incremental Sort
Sort Key: b, c DESC
Presorted Key: b
-> Group
Group Key: b, a, c
-> Sort
Sort Key: b, a, c
-> Seq Scan on t
If ORDER BY b, c DESC is added outside the window
to the same query, the GROUP BY item c takes that
DESC, and even master does it with one sort:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c ORDER BY b, c DESC;
-- master and patched
WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Group
Group Key: b, c, a
-> Sort
Sort Key: b, c DESC, a
-> Seq Scan on t
That grouping sort, b, c DESC, a, is exactly the order
the window needs. It would be nice if the patch could
pick it without the ORDER BY outside the window.
Please also consider the case where the ORDER BY outside
the window has a different direction from the window's.
With c DESC in the window and b, c outside, both master
and the patch do one full sort and two incremental sorts:
EXPLAIN (COSTS OFF)
SELECT a, b, c, count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c ORDER BY b, c;
-- patched (master differs only in grouping on b, c, a)
Incremental Sort
Sort Key: b, c
Presorted Key: b
-> WindowAgg
Window: w1 AS (PARTITION BY b ORDER BY c)
-> Incremental Sort
Sort Key: b, c DESC
Presorted Key: b
-> Group
Group Key: b, a, c
-> Sort
Sort Key: b, a, c
-> Seq Scan on t
Right now the plan sorts c ascending for the grouping,
descending for the window, and ascending again for the
ORDER BY outside the window. If the grouping sort followed the
window's sort, one of the incremental sorts would go away.
One thing to watch out for when implementing this: in this
query the GROUP BY item c has already taken the ascending
direction from the ORDER BY outside the window. So this cannot
be solved by looking only at the relation between the window's
ORDER BY and GROUP BY; the relations with the ORDER BY outside
the window and with PARTITION BY have to be taken into account
as well. Also, if the ORDER BY outside the window brought in a
different equality operator (ORDER BY ... USING), that changes
what counts as a group, so the GROUP BY item should follow the
window's direction only when the equality operator is the same.
Best regards,
Henson
Re: [PATCH] Consider window functions when reordering GROUP BY items
От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Zhenglong,
Thanks for v2. With both patches applied on master, make check
passes and every plan in your mail comes out as shown.
I did find two cases where a query that works on master gets slower
or fails with v2.
> 0002 is the window patch with the change you suggested, rebased on
> 0001.
1. Partial aggregation below a join goes away.
When a window sorts a GROUP BY column in descending order, the
partial aggregation that master does below the join off an ascending
index is gone in v2:
CREATE TABLE ea (i1 int, i2 int, x int);
INSERT INTO ea SELECT i % 100, (i / 100) % 1000, i
FROM generate_series(1, 1000000) i;
CREATE INDEX ON ea (i1, i2);
CREATE TABLE eb (k int, v int);
INSERT INTO eb SELECT i, i FROM generate_series(0, 99) i;
VACUUM ANALYZE ea, eb;
SET enable_hashagg = off;
EXPLAIN (COSTS OFF)
SELECT a.i1, a.i2, sum(a.x),
count(*) OVER (PARTITION BY a.i1 ORDER BY a.i2 DESC)
FROM ea a JOIN eb b ON a.i1 = b.k
GROUP BY a.i1, a.i2;
-- master
WindowAgg
-> Incremental Sort
Sort Key: a.i1, a.i2 DESC
Presorted Key: a.i1
-> Finalize GroupAggregate
Group Key: a.i1, a.i2
-> Merge Join
Merge Cond: (a.i1 = b.k)
-> Partial GroupAggregate
Group Key: a.i1, a.i2
-> Index Scan using ea_i1_i2_idx on ea a
...
-- v2
WindowAgg
-> Incremental Sort
Sort Key: a.i1, a.i2 DESC
Presorted Key: a.i1
-> GroupAggregate
Group Key: a.i1, a.i2
-> Merge Join
Merge Cond: (a.i1 = b.k)
-> Index Scan using ea_i1_i2_idx on ea a
...
The Incremental Sort for the window stays either way, so nothing is
gained; only the cost and the run time go up.
> 0001 lets [...] match an input pathkey with
> the same equivalence class and operator family regardless of
> direction
2. GROUP BY fails on an operator class without the reverse operator.
With a btree operator class that has only the less-than and equals
operators, a GROUP BY that works on master fails in v2 with a
"should not happen" error:
CREATE TYPE color AS ENUM ('r', 'g', 'b');
CREATE FUNCTION color_lt(color, color) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_lt';
CREATE FUNCTION color_eq(color, color) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_eq';
CREATE FUNCTION color_cmp(color, color) RETURNS int
LANGUAGE internal IMMUTABLE STRICT AS 'enum_cmp';
CREATE OPERATOR <<< (leftarg = color, rightarg = color,
function = color_lt);
CREATE OPERATOR === (leftarg = color, rightarg = color,
function = color_eq);
CREATE OPERATOR CLASS color_ops DEFAULT FOR TYPE color
USING btree AS
OPERATOR 1 <<<, OPERATOR 3 ===,
FUNCTION 1 color_cmp(color, color);
CREATE TABLE tc (c color);
INSERT INTO tc SELECT (ARRAY['r', 'g', 'b'])[1 + i % 3]::color
FROM generate_series(1, 3000) i;
CREATE INDEX ON tc (c);
ANALYZE tc;
SELECT c, count(*) FROM tc GROUP BY c;
-- master: the counts for r, g and b
-- v2: ERROR: missing operator 5(...) in opfamily ...
Such an operator class breaks the btree rules. Still, the missing
operator is needed only for one plan being considered, not for the
result, so wouldn't it be better to skip that plan than to raise an
error?
For the tests, I'd add:
- The two cases above.
- A query with two windows. None of the new queries in window.sql
has more than one OVER. For example, with two windows sorting c in
opposite directions, v2 does one sort fewer than master:
SELECT a, b, c,
count(*) OVER (PARTITION BY b ORDER BY c),
count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c;
- The groupwin result check. The test EXPLAINs one query and runs
another, and thanks to its outer ORDER BY the one it runs has the
same plan as on master, so the result it checks does not come from
v2's change. Wrapped in a subquery, master sorts twice and v2
once, so the result comes from the plan that v2 changes. Cases
like this, where the GROUP BY keys take the window's direction,
are where results most need checking:
SELECT * FROM
(SELECT x, z, count(*) c,
sum(count(*)) OVER (PARTITION BY x
ORDER BY z DESC NULLS LAST) s
FROM groupwin GROUP BY x, z) ss
ORDER BY x, z DESC NULLS LAST;
I tried such cases with different directions in the outer ORDER
BY, joins, outer windows and LIMIT, and the results all matched
master.
Best regards,
Henson
Thanks for v2. With both patches applied on master, make check
passes and every plan in your mail comes out as shown.
I did find two cases where a query that works on master gets slower
or fails with v2.
> 0002 is the window patch with the change you suggested, rebased on
> 0001.
1. Partial aggregation below a join goes away.
When a window sorts a GROUP BY column in descending order, the
partial aggregation that master does below the join off an ascending
index is gone in v2:
CREATE TABLE ea (i1 int, i2 int, x int);
INSERT INTO ea SELECT i % 100, (i / 100) % 1000, i
FROM generate_series(1, 1000000) i;
CREATE INDEX ON ea (i1, i2);
CREATE TABLE eb (k int, v int);
INSERT INTO eb SELECT i, i FROM generate_series(0, 99) i;
VACUUM ANALYZE ea, eb;
SET enable_hashagg = off;
EXPLAIN (COSTS OFF)
SELECT a.i1, a.i2, sum(a.x),
count(*) OVER (PARTITION BY a.i1 ORDER BY a.i2 DESC)
FROM ea a JOIN eb b ON a.i1 = b.k
GROUP BY a.i1, a.i2;
-- master
WindowAgg
-> Incremental Sort
Sort Key: a.i1, a.i2 DESC
Presorted Key: a.i1
-> Finalize GroupAggregate
Group Key: a.i1, a.i2
-> Merge Join
Merge Cond: (a.i1 = b.k)
-> Partial GroupAggregate
Group Key: a.i1, a.i2
-> Index Scan using ea_i1_i2_idx on ea a
...
-- v2
WindowAgg
-> Incremental Sort
Sort Key: a.i1, a.i2 DESC
Presorted Key: a.i1
-> GroupAggregate
Group Key: a.i1, a.i2
-> Merge Join
Merge Cond: (a.i1 = b.k)
-> Index Scan using ea_i1_i2_idx on ea a
...
The Incremental Sort for the window stays either way, so nothing is
gained; only the cost and the run time go up.
> 0001 lets [...] match an input pathkey with
> the same equivalence class and operator family regardless of
> direction
2. GROUP BY fails on an operator class without the reverse operator.
With a btree operator class that has only the less-than and equals
operators, a GROUP BY that works on master fails in v2 with a
"should not happen" error:
CREATE TYPE color AS ENUM ('r', 'g', 'b');
CREATE FUNCTION color_lt(color, color) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_lt';
CREATE FUNCTION color_eq(color, color) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_eq';
CREATE FUNCTION color_cmp(color, color) RETURNS int
LANGUAGE internal IMMUTABLE STRICT AS 'enum_cmp';
CREATE OPERATOR <<< (leftarg = color, rightarg = color,
function = color_lt);
CREATE OPERATOR === (leftarg = color, rightarg = color,
function = color_eq);
CREATE OPERATOR CLASS color_ops DEFAULT FOR TYPE color
USING btree AS
OPERATOR 1 <<<, OPERATOR 3 ===,
FUNCTION 1 color_cmp(color, color);
CREATE TABLE tc (c color);
INSERT INTO tc SELECT (ARRAY['r', 'g', 'b'])[1 + i % 3]::color
FROM generate_series(1, 3000) i;
CREATE INDEX ON tc (c);
ANALYZE tc;
SELECT c, count(*) FROM tc GROUP BY c;
-- master: the counts for r, g and b
-- v2: ERROR: missing operator 5(...) in opfamily ...
Such an operator class breaks the btree rules. Still, the missing
operator is needed only for one plan being considered, not for the
result, so wouldn't it be better to skip that plan than to raise an
error?
For the tests, I'd add:
- The two cases above.
- A query with two windows. None of the new queries in window.sql
has more than one OVER. For example, with two windows sorting c in
opposite directions, v2 does one sort fewer than master:
SELECT a, b, c,
count(*) OVER (PARTITION BY b ORDER BY c),
count(*) OVER (PARTITION BY b ORDER BY c DESC)
FROM t GROUP BY a, b, c;
- The groupwin result check. The test EXPLAINs one query and runs
another, and thanks to its outer ORDER BY the one it runs has the
same plan as on master, so the result it checks does not come from
v2's change. Wrapped in a subquery, master sorts twice and v2
once, so the result comes from the plan that v2 changes. Cases
like this, where the GROUP BY keys take the window's direction,
are where results most need checking:
SELECT * FROM
(SELECT x, z, count(*) c,
sum(count(*)) OVER (PARTITION BY x
ORDER BY z DESC NULLS LAST) s
FROM groupwin GROUP BY x, z) ss
ORDER BY x, z DESC NULLS LAST;
I tried such cases with different directions in the outer ORDER
BY, joins, outer windows and LIMIT, and the results all matched
master.
Best regards,
Henson
Re: [PATCH] Consider window functions when reordering GROUP BY items
Hi Henson,
Thanks for the careful review and for the reproducers. Both cases are
fixed in the attached v3, and the tests you suggested are added.
> 1. Partial aggregation below a join goes away.
The window turned out to be incidental. The same thing happens with v2
and no window at all:
SELECT a.i1, a.i2, sum(a.x)
FROM ea a JOIN eb b ON a.i1 = b.k
GROUP BY a.i1, a.i2
ORDER BY a.i1, a.i2 DESC;
Here the parser already gives the GROUP BY item i2 the ORDER BY's DESC,
so 0002 plays no part. The cause is in 0001: it let the final
aggregation group straight off the (i1, i2) index regardless of
direction, but generate_grouped_paths() still required its input to be
sorted exactly by the grouping pathkeys. The partial aggregation
therefore still had to sort its whole input, and lost to the plan
without it, which had just become cheaper. 0002 merely brings the
window queries into the same situation by giving i2 the window's
direction.
v3 lets the partial aggregation take the sort direction from its input
path as well. Like the final aggregation, it compares the grouping
keys only for equality, and its output keeps the ordering of its
input, so nothing else changes: agg_info->group_clauses stays as is,
and only the pathkeys used to decide whether and how to sort the input
are adjusted, by a new function adjust_group_pathkeys_to_input().
With that, your query does the partial aggregation off the index
again, and a single Incremental Sort by (i1, i2 DESC) above the Merge
Join, over the ~100k partially aggregated rows, serves both the
Finalize GroupAggregate and the WindowAgg (excerpt):
WindowAgg
Window: w1 AS (PARTITION BY a.i1 ORDER BY a.i2)
-> Finalize GroupAggregate
Group Key: a.i1, a.i2
-> Gather Merge
Workers Planned: 2
-> Incremental Sort
Sort Key: a.i1, a.i2 DESC
Presorted Key: a.i1
-> Merge Join
Merge Cond: (a.i1 = b.k)
-> Partial GroupAggregate
Group Key: a.i1, a.i2
-> Parallel Index Scan using ea_i1_i2_idx on ea a
-> Sort
Sort Key: b.k
-> Seq Scan on eb b
Timings on your data set (5 runs each, same -O2 build type for all):
master v2 v3
window query 209-240 ms 235-271 ms 99-107 ms
ORDER BY query 183-193 ms 218-255 ms 104-114 ms
The results match master for both queries.
> 2. GROUP BY fails on an operator class without the reverse operator.
Agreed, skipping the plan is better. In v3,
group_keys_reorder_by_pathkeys() looks up the operator before adding
the key to the reordered list. If the operator family lacks it, the
function stops matching there, just as it does on any other mismatch,
and the GROUP BY keys from that point on are sorted in their own
direction. Your query now returns 1000 for each color.
Thanks again for testing all those combinations of outer ORDER BY,
joins, outer windows and LIMIT.
Regards,
Zhenglong Li
Thanks for the careful review and for the reproducers. Both cases are
fixed in the attached v3, and the tests you suggested are added.
> 1. Partial aggregation below a join goes away.
The window turned out to be incidental. The same thing happens with v2
and no window at all:
SELECT a.i1, a.i2, sum(a.x)
FROM ea a JOIN eb b ON a.i1 = b.k
GROUP BY a.i1, a.i2
ORDER BY a.i1, a.i2 DESC;
Here the parser already gives the GROUP BY item i2 the ORDER BY's DESC,
so 0002 plays no part. The cause is in 0001: it let the final
aggregation group straight off the (i1, i2) index regardless of
direction, but generate_grouped_paths() still required its input to be
sorted exactly by the grouping pathkeys. The partial aggregation
therefore still had to sort its whole input, and lost to the plan
without it, which had just become cheaper. 0002 merely brings the
window queries into the same situation by giving i2 the window's
direction.
v3 lets the partial aggregation take the sort direction from its input
path as well. Like the final aggregation, it compares the grouping
keys only for equality, and its output keeps the ordering of its
input, so nothing else changes: agg_info->group_clauses stays as is,
and only the pathkeys used to decide whether and how to sort the input
are adjusted, by a new function adjust_group_pathkeys_to_input().
With that, your query does the partial aggregation off the index
again, and a single Incremental Sort by (i1, i2 DESC) above the Merge
Join, over the ~100k partially aggregated rows, serves both the
Finalize GroupAggregate and the WindowAgg (excerpt):
WindowAgg
Window: w1 AS (PARTITION BY a.i1 ORDER BY a.i2)
-> Finalize GroupAggregate
Group Key: a.i1, a.i2
-> Gather Merge
Workers Planned: 2
-> Incremental Sort
Sort Key: a.i1, a.i2 DESC
Presorted Key: a.i1
-> Merge Join
Merge Cond: (a.i1 = b.k)
-> Partial GroupAggregate
Group Key: a.i1, a.i2
-> Parallel Index Scan using ea_i1_i2_idx on ea a
-> Sort
Sort Key: b.k
-> Seq Scan on eb b
Timings on your data set (5 runs each, same -O2 build type for all):
master v2 v3
window query 209-240 ms 235-271 ms 99-107 ms
ORDER BY query 183-193 ms 218-255 ms 104-114 ms
The results match master for both queries.
> 2. GROUP BY fails on an operator class without the reverse operator.
Agreed, skipping the plan is better. In v3,
group_keys_reorder_by_pathkeys() looks up the operator before adding
the key to the reordered list. If the operator family lacks it, the
function stops matching there, just as it does on any other mismatch,
and the GROUP BY keys from that point on are sorted in their own
direction. Your query now returns 1000 for each color.
Thanks again for testing all those combinations of outer ORDER BY,
joins, outer windows and LIMIT.
Regards,
Zhenglong Li
Re: [PATCH] Consider window functions when reordering GROUP BY items
Hi Zhenglong,
Thanks for v3. With both patches applied on master, make check
passes. The window query from my last mail does the partial
aggregation off the index again, and both queries from that mail
now return the same results as master.
This time I built a test matrix and audited v3 against it with AI
tools: plain, partial, eager, partitionwise and parallel
aggregation, DISTINCT, grouping sets, merge joins, postgres_fdw and
windows, plus operator classes missing an operator, and random
queries whose results were compared with master. The numbers
below come from those runs.
Overall, I think the patch is a clear win. Of about 170 queries
without windows, mostly GROUP BY, 43 change plans with 0001. Run
time relative to master (release build; "same" is within 3%):
changed faster same slower
ORDER BY 15 14 0.26-0.93 1 -
ORDER BY + LIMIT 8 8 0.63-0.85 - -
ordered aggregate 2 2 0.46-0.57 - -
count(DISTINCT) 1 1 0.54 - -
partitionwise 5 3 0.46-0.57 - 2 1.10-1.34
postgres_fdw (*) 1 1 0.18 - -
join 2 - - 2 1.08
small work_mem 2 1 0.76 1 -
ORDER BY, 2M rows 7 - 2 5 1.10-2.28
total 43 30 4 9
(*) assert-enabled build; the aggregate and the LIMIT are now
pushed down to the remote side.
The "same" one under ORDER BY is a near tie in cost: its plan
changes in the assert-enabled build but not in the release build.
The attached cf7150-matrix.sql builds the data and runs these 43
queries, so the plans and ratios can be checked on master and with
the patch. Ratios close to 1.0 can move between columns from run
to run.
- The slower ones mostly come from the existing cost model, which
I think belongs in a separate patch rather than this one
(item 4).
- Your window and ORDER BY queries on ea/eb also reproduce: with
enable_hashagg = off as in my last mail, about 250 -> 105 ms and
185 -> 105 ms (assert-enabled build).
- One large loss, where a window takes away master's better plan
(item 2 below). I think it can be fixed as suggested there.
- Planning takes a bit longer, which I see as a trade-off worth
accepting (item 3).
There is also one error left (item 1).
> In v3,
> group_keys_reorder_by_pathkeys() looks up the operator before adding
> the key to the reordered list.
1. The missing operator error still happens with eager aggregation.
If the operator class also has FUNCTION 4, so that the GROUP BY can
be pushed below a join, the same error comes back, with every setting
at its default:
CREATE TYPE col3 AS ENUM ('r', 'g', 'b');
CREATE FUNCTION col3_lt(col3, col3) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_lt';
CREATE FUNCTION col3_eq(col3, col3) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_eq';
CREATE FUNCTION col3_cmp(col3, col3) RETURNS int
LANGUAGE internal IMMUTABLE STRICT AS 'enum_cmp';
CREATE OPERATOR <<< (leftarg = col3, rightarg = col3,
function = col3_lt);
CREATE OPERATOR === (leftarg = col3, rightarg = col3,
function = col3_eq);
CREATE OPERATOR CLASS col3_ops DEFAULT FOR TYPE col3
USING btree AS
OPERATOR 1 <<<, OPERATOR 3 ===,
FUNCTION 1 col3_cmp(col3, col3),
FUNCTION 4 btequalimage(oid);
CREATE TABLE ec3 (c col3, d int, x int);
INSERT INTO ec3
SELECT (ARRAY['r', 'g', 'b'])[1 + i % 3]::col3, i % 50, i
FROM generate_series(1, 60000) i;
CREATE INDEX ON ec3 (c DESC) INCLUDE (d, x);
CREATE TABLE es3 (k int);
INSERT INTO es3 SELECT generate_series(0, 49);
VACUUM ANALYZE ec3, es3;
SELECT t.c, sum(t.x)
FROM ec3 t JOIN es3 s ON t.d = s.k
GROUP BY t.c;
-- master: 3 rows
-- v3: ERROR: missing operator 5(...) in opfamily ...
As before, such an operator class breaks the btree rules. Still,
the query works on master, so this is a regression.
I'd add a test like this next to the color one: the same kind of
operator class, with FUNCTION 4 and a join.
> 0002 merely brings the window queries into the same situation by
> giving i2 the window's direction.
2. Giving the GROUP BY the window's direction can lose a better plan.
When the window sorts the leading GROUP BY column in descending
order, master's plan from an ascending index is gone in v3:
CREATE TABLE ts (a int, b int, c int);
INSERT INTO ts
SELECT i % 5, CASE WHEN i % 4 = 0 THEN NULL ELSE i % 3 END,
i % 2
FROM generate_series(1, 300) i;
ANALYZE ts;
CREATE TABLE tb (a int, b int, c int);
INSERT INTO tb SELECT i % 7, (i * 7) % 11, i % 5
FROM generate_series(1, 1000000) i;
CREATE INDEX ON tb (a, b);
VACUUM ANALYZE tb;
EXPLAIN (COSTS OFF)
SELECT tb.a, count(*), sum(count(*)) OVER (ORDER BY tb.a DESC)
FROM tb JOIN ts ON tb.a = ts.a AND tb.b = ts.b
GROUP BY tb.a;
-- master (cost 38261)
WindowAgg
-> Sort
Sort Key: tb.a DESC
-> Finalize GroupAggregate
Group Key: tb.a
-> Gather Merge
-> Partial GroupAggregate
Group Key: tb.a
-> Merge Join
Merge Cond: ((tb.a = ts.a) AND
(tb.b = ts.b))
-> Parallel Index Only Scan
using tb_a_b_idx on tb
-> Sort
Sort Key: ts.a, ts.b
-> Seq Scan on ts
-- v3 (cost 67642)
WindowAgg
-> Sort
Sort Key: tb.a DESC
-> HashAggregate
Group Key: tb.a
-> Nested Loop
-> Seq Scan on ts
-> Memoize
-> Index Only Scan
using tb_a_b_idx on tb
The Sort for the window stays in both plans, so v3 gains nothing
here, and the query takes about twice as long as on master: 191-194
ms against 95-101 ms (5 runs each, assert-enabled build).
The window's direction is applied to the GROUP BY keys before any
paths are built, so the ascending plan is never considered. Would
it work to offer the window's ordering as one more candidate, next
to the orderings that get_useful_group_keys_orderings() already
returns, and let the cost decide? If that works, I'd expect a
query like this to keep master's plan, while your queries can still
choose the window's ordering when it is cheaper.
I'd add this query as a test as well.
3. Planning time.
With 0001, more paths with the reverse direction survive, so
planning takes a bit longer. Measured on the ea/eb tables from
item 1 of my last mail, the same data you timed v3 on (median of 20
EXPLAINs in one session, best of 5 sessions; execution best to
worst of 5 runs; default settings; assert-enabled build):
planning (ms) execution (ms)
master v3-0001 v3 master v3
GROUP BY 0.022 0.027 0.027 120-126 120-122
+ ORDER BY DESC 0.024 0.031 0.032 113-119 114-120
+ window DESC 0.025 0.031 0.034 165-171 134-139
-- GROUP BY:
SELECT a.i1, a.i2, sum(a.x)
FROM ea a JOIN eb b ON a.i1 = b.k
GROUP BY a.i1, a.i2;
-- + ORDER BY a.i1, a.i2 DESC, or
-- + count(*) OVER (PARTITION BY a.i1 ORDER BY a.i2 DESC)
That is 23-36% more, but only 5-9 microseconds. Considering more
orderings means more paths to build and compare, so I don't think
it can be avoided. And window functions are mostly used for
analytic queries, where spending microseconds more on planning to
save tens of milliseconds of execution, as in the last row, is a
good trade. So I don't see this as a problem.
4. The slower cases come from the existing cost model.
Most of the slower queries in the table pick an Index Scan over an
index that covers only part of the GROUP BY keys, followed by an
Incremental Sort. This pair is estimated cheaper than the other
plans but runs slower than some of them. master already makes the
same choice today:
CREATE TABLE big AS
SELECT i % 1000 AS a, i % 77 AS b, i % 5 AS c
FROM generate_series(1, 2000000) i;
CREATE INDEX ON big (a, b);
VACUUM ANALYZE big;
SELECT a, b, c, count(*) FROM big WHERE a < 500
GROUP BY a, b, c ORDER BY a, b, c;
default incremental sort off
master, ORDER BY a, b, c 282-304 ms 149-154 ms
v3, ORDER BY a, b DESC, c 290-308 ms 150-157 ms
On master (assert-enabled build):
cost actual
Index Scan + Incremental Sort (chosen) 108972 304 ms
Parallel Seq Scan + Sort, 2 workers 137517 164 ms
Bitmap Heap Scan + HashAggregate + Sort 137207 134 ms
Seq Scan + Sort, serial 166861 395 ms
The two plans in the middle run about twice as fast as the chosen
one but lose on the estimate. The nodes of the two serial plans
(own cost and time, up to the end of each node; 3 runs):
cost actual per 1000 cost
Index Scan 64510 162-165 ms 2.5 ms
Incremental Sort 32479 110-112 ms 3.4 ms
Seq Scan 35816 62-63 ms 1.7 ms
Sort (*) 119062 296-311 ms 2.5 ms
(*) external merge, 21616kB on disk with work_mem = 4MB
Per unit of cost, the Index Scan takes about 1.5 times as long as
the Seq Scan, and the Incremental Sort, over 19250 groups of
about 52 rows, about 1.3 times as long as the full Sort. So both
are underestimated. Correcting both would make the chosen plan
lose its 28235 lead, and most of that comes from the Index Scan.
0001 only lets mixed-direction queries reach the same plan as the
ascending ones, plus a final Incremental Sort for the ORDER BY. On
this small example master already picks a similar plan for the DESC
query too, so v3 is only about 10% slower here (259-279 ms on
master). So I think this should be fixed not in this patch
but in a separate one on the cost estimate of the Index Scan and
the Incremental Sort above it.
Once items 1 and 2 are addressed, I'll move on to a line-by-line
review of the code.
Best regards,
Henson
Thanks for v3. With both patches applied on master, make check
passes. The window query from my last mail does the partial
aggregation off the index again, and both queries from that mail
now return the same results as master.
This time I built a test matrix and audited v3 against it with AI
tools: plain, partial, eager, partitionwise and parallel
aggregation, DISTINCT, grouping sets, merge joins, postgres_fdw and
windows, plus operator classes missing an operator, and random
queries whose results were compared with master. The numbers
below come from those runs.
Overall, I think the patch is a clear win. Of about 170 queries
without windows, mostly GROUP BY, 43 change plans with 0001. Run
time relative to master (release build; "same" is within 3%):
changed faster same slower
ORDER BY 15 14 0.26-0.93 1 -
ORDER BY + LIMIT 8 8 0.63-0.85 - -
ordered aggregate 2 2 0.46-0.57 - -
count(DISTINCT) 1 1 0.54 - -
partitionwise 5 3 0.46-0.57 - 2 1.10-1.34
postgres_fdw (*) 1 1 0.18 - -
join 2 - - 2 1.08
small work_mem 2 1 0.76 1 -
ORDER BY, 2M rows 7 - 2 5 1.10-2.28
total 43 30 4 9
(*) assert-enabled build; the aggregate and the LIMIT are now
pushed down to the remote side.
The "same" one under ORDER BY is a near tie in cost: its plan
changes in the assert-enabled build but not in the release build.
The attached cf7150-matrix.sql builds the data and runs these 43
queries, so the plans and ratios can be checked on master and with
the patch. Ratios close to 1.0 can move between columns from run
to run.
- The slower ones mostly come from the existing cost model, which
I think belongs in a separate patch rather than this one
(item 4).
- Your window and ORDER BY queries on ea/eb also reproduce: with
enable_hashagg = off as in my last mail, about 250 -> 105 ms and
185 -> 105 ms (assert-enabled build).
- One large loss, where a window takes away master's better plan
(item 2 below). I think it can be fixed as suggested there.
- Planning takes a bit longer, which I see as a trade-off worth
accepting (item 3).
There is also one error left (item 1).
> In v3,
> group_keys_reorder_by_pathkeys() looks up the operator before adding
> the key to the reordered list.
1. The missing operator error still happens with eager aggregation.
If the operator class also has FUNCTION 4, so that the GROUP BY can
be pushed below a join, the same error comes back, with every setting
at its default:
CREATE TYPE col3 AS ENUM ('r', 'g', 'b');
CREATE FUNCTION col3_lt(col3, col3) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_lt';
CREATE FUNCTION col3_eq(col3, col3) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_eq';
CREATE FUNCTION col3_cmp(col3, col3) RETURNS int
LANGUAGE internal IMMUTABLE STRICT AS 'enum_cmp';
CREATE OPERATOR <<< (leftarg = col3, rightarg = col3,
function = col3_lt);
CREATE OPERATOR === (leftarg = col3, rightarg = col3,
function = col3_eq);
CREATE OPERATOR CLASS col3_ops DEFAULT FOR TYPE col3
USING btree AS
OPERATOR 1 <<<, OPERATOR 3 ===,
FUNCTION 1 col3_cmp(col3, col3),
FUNCTION 4 btequalimage(oid);
CREATE TABLE ec3 (c col3, d int, x int);
INSERT INTO ec3
SELECT (ARRAY['r', 'g', 'b'])[1 + i % 3]::col3, i % 50, i
FROM generate_series(1, 60000) i;
CREATE INDEX ON ec3 (c DESC) INCLUDE (d, x);
CREATE TABLE es3 (k int);
INSERT INTO es3 SELECT generate_series(0, 49);
VACUUM ANALYZE ec3, es3;
SELECT t.c, sum(t.x)
FROM ec3 t JOIN es3 s ON t.d = s.k
GROUP BY t.c;
-- master: 3 rows
-- v3: ERROR: missing operator 5(...) in opfamily ...
As before, such an operator class breaks the btree rules. Still,
the query works on master, so this is a regression.
I'd add a test like this next to the color one: the same kind of
operator class, with FUNCTION 4 and a join.
> 0002 merely brings the window queries into the same situation by
> giving i2 the window's direction.
2. Giving the GROUP BY the window's direction can lose a better plan.
When the window sorts the leading GROUP BY column in descending
order, master's plan from an ascending index is gone in v3:
CREATE TABLE ts (a int, b int, c int);
INSERT INTO ts
SELECT i % 5, CASE WHEN i % 4 = 0 THEN NULL ELSE i % 3 END,
i % 2
FROM generate_series(1, 300) i;
ANALYZE ts;
CREATE TABLE tb (a int, b int, c int);
INSERT INTO tb SELECT i % 7, (i * 7) % 11, i % 5
FROM generate_series(1, 1000000) i;
CREATE INDEX ON tb (a, b);
VACUUM ANALYZE tb;
EXPLAIN (COSTS OFF)
SELECT tb.a, count(*), sum(count(*)) OVER (ORDER BY tb.a DESC)
FROM tb JOIN ts ON tb.a = ts.a AND tb.b = ts.b
GROUP BY tb.a;
-- master (cost 38261)
WindowAgg
-> Sort
Sort Key: tb.a DESC
-> Finalize GroupAggregate
Group Key: tb.a
-> Gather Merge
-> Partial GroupAggregate
Group Key: tb.a
-> Merge Join
Merge Cond: ((tb.a = ts.a) AND
(tb.b = ts.b))
-> Parallel Index Only Scan
using tb_a_b_idx on tb
-> Sort
Sort Key: ts.a, ts.b
-> Seq Scan on ts
-- v3 (cost 67642)
WindowAgg
-> Sort
Sort Key: tb.a DESC
-> HashAggregate
Group Key: tb.a
-> Nested Loop
-> Seq Scan on ts
-> Memoize
-> Index Only Scan
using tb_a_b_idx on tb
The Sort for the window stays in both plans, so v3 gains nothing
here, and the query takes about twice as long as on master: 191-194
ms against 95-101 ms (5 runs each, assert-enabled build).
The window's direction is applied to the GROUP BY keys before any
paths are built, so the ascending plan is never considered. Would
it work to offer the window's ordering as one more candidate, next
to the orderings that get_useful_group_keys_orderings() already
returns, and let the cost decide? If that works, I'd expect a
query like this to keep master's plan, while your queries can still
choose the window's ordering when it is cheaper.
I'd add this query as a test as well.
3. Planning time.
With 0001, more paths with the reverse direction survive, so
planning takes a bit longer. Measured on the ea/eb tables from
item 1 of my last mail, the same data you timed v3 on (median of 20
EXPLAINs in one session, best of 5 sessions; execution best to
worst of 5 runs; default settings; assert-enabled build):
planning (ms) execution (ms)
master v3-0001 v3 master v3
GROUP BY 0.022 0.027 0.027 120-126 120-122
+ ORDER BY DESC 0.024 0.031 0.032 113-119 114-120
+ window DESC 0.025 0.031 0.034 165-171 134-139
-- GROUP BY:
SELECT a.i1, a.i2, sum(a.x)
FROM ea a JOIN eb b ON a.i1 = b.k
GROUP BY a.i1, a.i2;
-- + ORDER BY a.i1, a.i2 DESC, or
-- + count(*) OVER (PARTITION BY a.i1 ORDER BY a.i2 DESC)
That is 23-36% more, but only 5-9 microseconds. Considering more
orderings means more paths to build and compare, so I don't think
it can be avoided. And window functions are mostly used for
analytic queries, where spending microseconds more on planning to
save tens of milliseconds of execution, as in the last row, is a
good trade. So I don't see this as a problem.
4. The slower cases come from the existing cost model.
Most of the slower queries in the table pick an Index Scan over an
index that covers only part of the GROUP BY keys, followed by an
Incremental Sort. This pair is estimated cheaper than the other
plans but runs slower than some of them. master already makes the
same choice today:
CREATE TABLE big AS
SELECT i % 1000 AS a, i % 77 AS b, i % 5 AS c
FROM generate_series(1, 2000000) i;
CREATE INDEX ON big (a, b);
VACUUM ANALYZE big;
SELECT a, b, c, count(*) FROM big WHERE a < 500
GROUP BY a, b, c ORDER BY a, b, c;
default incremental sort off
master, ORDER BY a, b, c 282-304 ms 149-154 ms
v3, ORDER BY a, b DESC, c 290-308 ms 150-157 ms
On master (assert-enabled build):
cost actual
Index Scan + Incremental Sort (chosen) 108972 304 ms
Parallel Seq Scan + Sort, 2 workers 137517 164 ms
Bitmap Heap Scan + HashAggregate + Sort 137207 134 ms
Seq Scan + Sort, serial 166861 395 ms
The two plans in the middle run about twice as fast as the chosen
one but lose on the estimate. The nodes of the two serial plans
(own cost and time, up to the end of each node; 3 runs):
cost actual per 1000 cost
Index Scan 64510 162-165 ms 2.5 ms
Incremental Sort 32479 110-112 ms 3.4 ms
Seq Scan 35816 62-63 ms 1.7 ms
Sort (*) 119062 296-311 ms 2.5 ms
(*) external merge, 21616kB on disk with work_mem = 4MB
Per unit of cost, the Index Scan takes about 1.5 times as long as
the Seq Scan, and the Incremental Sort, over 19250 groups of
about 52 rows, about 1.3 times as long as the full Sort. So both
are underestimated. Correcting both would make the chosen plan
lose its 28235 lead, and most of that comes from the Index Scan.
0001 only lets mixed-direction queries reach the same plan as the
ascending ones, plus a final Incremental Sort for the ORDER BY. On
this small example master already picks a similar plan for the DESC
query too, so v3 is only about 10% slower here (259-279 ms on
master). So I think this should be fixed not in this patch
but in a separate one on the cost estimate of the Index Scan and
the Incremental Sort above it.
Once items 1 and 2 are addressed, I'll move on to a line-by-line
review of the code.
Best regards,
Henson
Re: [PATCH] Consider window functions when reordering GROUP BY items
Hi Henson,
Thanks for the review and for the test matrix, it was very helpful.
v4 is attached.
> 1. The missing operator error still happens with eager aggregation.
Fixed. The check in v3 was only in group_keys_reorder_by_pathkeys(),
but the partial aggregation goes through adjust_group_pathkeys_to_input(),
which took the input's DESC pathkey without checking the operator. Now
it stops there if the opfamily don't have the operator for that
direction. Your query returns 3 rows like master, and I added it to
eager_aggregate.sql.
> Would it work to offer the window's ordering as one more candidate,
> next to the orderings that get_useful_group_keys_orderings() already
> returns, and let the cost decide?
Yes, that works. preprocess_groupclause() is back to master, and the
window ordering is now just one more candidate in
get_useful_group_keys_orderings(). I also had to add it in
gather_grouping_paths(), otherwise the sort for the window ordering
is done by the leader above Gather Merge and the ea/eb query lose
most of the gain.
Numbers (5 runs, ms, -O2 with assertions):
master v3 v4
your tb/ts query 85-91 181-189 65-76
ea/eb window 223-257 106-123 117-138
Your tb/ts query is now in window.sql. While running check-world I
noticed the plan there depend on the visibility map, so the test
disables nestloop and hashjoin to keep it stable.
> 3. Planning time.
I re-measured the same way as you did. v4 is about the same as v3
(0.89-1.01x), the window query is ~13us more than master.
> 4. The slower cases come from the existing cost model.
Agree, I'd leave it for a separate patch. I reran cf7150-matrix.sql
on v4, it's 35 faster and 7 slower out of 42 changed plans, and the
slower ones all have the Index Scan + Incremental Sort shape you
described.
Two behavior changes from v3 that I should mention:
- The skipping of redundant sort clauses (e.g. "ORDER BY x USING ~<~,
x, y") is gone, since it was part of preprocess_groupclause()
changes. That query plans same as master now.
- The window ordering now follows enable_group_by_reordering, like the
other reorderings. In v3 it was applied always.
Regards,
Zhenglong Li
Thanks for the review and for the test matrix, it was very helpful.
v4 is attached.
> 1. The missing operator error still happens with eager aggregation.
Fixed. The check in v3 was only in group_keys_reorder_by_pathkeys(),
but the partial aggregation goes through adjust_group_pathkeys_to_input(),
which took the input's DESC pathkey without checking the operator. Now
it stops there if the opfamily don't have the operator for that
direction. Your query returns 3 rows like master, and I added it to
eager_aggregate.sql.
> Would it work to offer the window's ordering as one more candidate,
> next to the orderings that get_useful_group_keys_orderings() already
> returns, and let the cost decide?
Yes, that works. preprocess_groupclause() is back to master, and the
window ordering is now just one more candidate in
get_useful_group_keys_orderings(). I also had to add it in
gather_grouping_paths(), otherwise the sort for the window ordering
is done by the leader above Gather Merge and the ea/eb query lose
most of the gain.
Numbers (5 runs, ms, -O2 with assertions):
master v3 v4
your tb/ts query 85-91 181-189 65-76
ea/eb window 223-257 106-123 117-138
Your tb/ts query is now in window.sql. While running check-world I
noticed the plan there depend on the visibility map, so the test
disables nestloop and hashjoin to keep it stable.
> 3. Planning time.
I re-measured the same way as you did. v4 is about the same as v3
(0.89-1.01x), the window query is ~13us more than master.
> 4. The slower cases come from the existing cost model.
Agree, I'd leave it for a separate patch. I reran cf7150-matrix.sql
on v4, it's 35 faster and 7 slower out of 42 changed plans, and the
slower ones all have the Index Scan + Incremental Sort shape you
described.
Two behavior changes from v3 that I should mention:
- The skipping of redundant sort clauses (e.g. "ORDER BY x USING ~<~,
x, y") is gone, since it was part of preprocess_groupclause()
changes. That query plans same as master now.
- The window ordering now follows enable_group_by_reordering, like the
other reorderings. In v3 it was applied always.
Regards,
Zhenglong Li
Re: [PATCH] Consider window functions when reordering GROUP BY items
Hi Zhenglong,
> v4 is attached.
Thanks for v4. With both patches applied on master, make check
passes, the eager aggregation query from my last mail returns its
rows again, and the tb/ts query keeps master's merge join over the
index. To wrap up my review, here is what the patch changes,
including the small incremental patch attached.
Sorting is one of the expensive steps of a plan. It grows
faster than its input and spills to disk once it exceeds work_mem.
A query with GROUP BY, window functions and ORDER BY may sort up to
three times, and a sort goes away when the output order of one step
already satisfies the order the next step needs. Grouping itself
only needs equal values to be adjacent, so choosing the grouping
order well costs nothing and can save sorts. Today the grouping
order is matched only to the query's ORDER BY, and its sort
direction is taken from ORDER BY as well. So an index sorted in
the other direction can't be used for grouping, and with window
functions one more sort happens for the window right above the
grouping step.
With the patch, users see three changes.
- An index or an already sorted input can be used for grouping even
if its direction differs from ORDER BY. For example, with an
index on (b, c), "GROUP BY b, c ORDER BY b, c DESC" can group
straight off the index and sort only the (typically far fewer)
groups for ORDER BY, when grouping by sort is chosen over
hashing. The same goes for the partial aggregation that eager
aggregation pushes below a join.
- With window functions, one sort can serve both the grouping and
the first window. "GROUP BY a, b" with "OVER (PARTITION BY b)"
used to sort twice when grouping by sort, by (a, b) and by (b);
now it sorts once, by (b, a). In parallel plans the workers
share this sort.
- This is only an option. The planner compares the old and the new
orderings and takes the cheaper one, and turning
enable_group_by_reordering off gives the old plans.
To do this, a grouping key and a sort key are taken to match if they
are on the same column with the same comparison semantics (the same
equivalence class and operator family), even if their sort direction
and NULLS position differ. When another direction is taken, it goes
only into the planner's own copy of the grouping clause, so the query
as written is unchanged, and so is the output of view definitions. The
window-matched ordering is an extra candidate that puts the first
window's PARTITION BY and ORDER BY keys first and keeps the remaining
keys in ORDER BY order. The ordering used to plan the scans and joins
below stays as before, so an index that provides the old ordering
cheaply is not lost. In parallel plans the workers sort in either
ordering before the results are gathered.
The incremental patch changes two things, and adds tests.
> - The window ordering now follows enable_group_by_reordering, like the
> other reorderings. In v3 it was applied always.
Not only the window ordering. With the setting off, v4 still does
the direction-insensitive matching in truncate_useless_pathkeys()
and adjust_group_pathkeys_to_input(), so the d1/d2 query in
eager_aggregate.sql gets a different plan from master. The
incremental patch checks the setting there too, and adds that query
with the setting off to the test.
> 1. The missing operator error still happens with eager aggregation.
> Fixed. The check in v3 was only in group_keys_reorder_by_pathkeys(),
> but the partial aggregation goes through adjust_group_pathkeys_to_input(),
> which took the input's DESC pathkey without checking the operator. Now
> it stops there if the opfamily don't have the operator for that
> direction.
Here I take back my request from the last mail. The guard covers
only one path: with the same operator class, a merge join over the
backward index path still fails on v4 with "missing operator". On
the other hand, a btree operator class must provide all five
comparison operators (btree.sgml), and master already fails on such
a class with ORDER BY c DESC. So the incremental patch removes the
guard and its two tests, and the eager aggregation query from my
last mail fails again (it works with enable_group_by_reordering
off).
But that isn't mine to decide, so I'd like to know where the
consensus among committers is: should the planner keep working with
a btree operator class missing an operator, or can it be treated as
unsupported?
As for the tests, I wanted to know which parts of the patch the
regression tests actually pin, so I changed the patched code one
place at a time (mutation testing) and ran make check. Of 11 such
changes only one, dropping the window candidate in
get_useful_group_keys_orderings(), made a test fail. The
incremental patch adds tests that catch most of the others that
change a plan.
As for performance, these are from a release build, alternating
with master on a shared machine, so please read them as ranges.
master v4
your tb/ts query 74-86 ms 56-63 ms
ea/eb, hashagg off 181-192 ms 82-88 ms
43 queries from my last mail 42 change plans: 30 faster
(0.18-0.94x), 3 within 3%,
9 slower (1.05-2.28x)
planning time +2-6 us without windows (up to
+22 us on two join queries),
+3-8 us with windows
The window gains all come from 0002. The incremental patch doesn't
change plans with default settings, so these numbers still hold.
The nine slower ones get the same plans with 0001 alone; they are
mostly the Index Scan + Incremental Sort shape, the existing cost
estimate problem we agreed to leave for a separate patch. CREATE
STATISTICS (ndistinct) on the grouping columns fixes two of them
(2.2x and 1.25x). For three (1.1-1.3x) it only makes master pick
the same slower plan, and four (1.03-1.16x) stay, mostly because
uncorrelated Index Scans and Incremental Sort over many small groups
are costed too low.
One slower case is not in the matrix and comes from 0002: a window
query over 2M rows goes from HashAggregate + Sort (~220 ms) to Sort +
GroupAggregate (~900 ms), because x % 4 is estimated through x (2M
groups expected, 77k actual). CREATE STATISTICS ON (x % 4) fixes it;
ndistinct on the plain columns doesn't. With enable_hashagg off, the
window ordering can also put a low-cardinality key first in a large
sort, which runs 25-40% slower at the same cost, as the sort cost
doesn't depend on key order; master has the same weakness with
ORDER BY.
To sum up, the gains are broad and large, and I found no wrong
results. The losses are rare and come not from the patch's logic
but from existing limits of the planner's estimates and cost model:
group count estimates, a sort cost that ignores key order, and Index
Scans and Incremental Sorts costed too low. The patch does give
those limits more chances to show, since it offers more orderings,
and a badly wrong estimate can make a query several times slower at
default settings. Some cases are fixed by extended statistics; the
rest need cost model work, which I'd keep separate.
Based on the above, with the attached incremental patch, +1 from
me.
Best regards,
Henson
> v4 is attached.
Thanks for v4. With both patches applied on master, make check
passes, the eager aggregation query from my last mail returns its
rows again, and the tb/ts query keeps master's merge join over the
index. To wrap up my review, here is what the patch changes,
including the small incremental patch attached.
Sorting is one of the expensive steps of a plan. It grows
faster than its input and spills to disk once it exceeds work_mem.
A query with GROUP BY, window functions and ORDER BY may sort up to
three times, and a sort goes away when the output order of one step
already satisfies the order the next step needs. Grouping itself
only needs equal values to be adjacent, so choosing the grouping
order well costs nothing and can save sorts. Today the grouping
order is matched only to the query's ORDER BY, and its sort
direction is taken from ORDER BY as well. So an index sorted in
the other direction can't be used for grouping, and with window
functions one more sort happens for the window right above the
grouping step.
With the patch, users see three changes.
- An index or an already sorted input can be used for grouping even
if its direction differs from ORDER BY. For example, with an
index on (b, c), "GROUP BY b, c ORDER BY b, c DESC" can group
straight off the index and sort only the (typically far fewer)
groups for ORDER BY, when grouping by sort is chosen over
hashing. The same goes for the partial aggregation that eager
aggregation pushes below a join.
- With window functions, one sort can serve both the grouping and
the first window. "GROUP BY a, b" with "OVER (PARTITION BY b)"
used to sort twice when grouping by sort, by (a, b) and by (b);
now it sorts once, by (b, a). In parallel plans the workers
share this sort.
- This is only an option. The planner compares the old and the new
orderings and takes the cheaper one, and turning
enable_group_by_reordering off gives the old plans.
To do this, a grouping key and a sort key are taken to match if they
are on the same column with the same comparison semantics (the same
equivalence class and operator family), even if their sort direction
and NULLS position differ. When another direction is taken, it goes
only into the planner's own copy of the grouping clause, so the query
as written is unchanged, and so is the output of view definitions. The
window-matched ordering is an extra candidate that puts the first
window's PARTITION BY and ORDER BY keys first and keeps the remaining
keys in ORDER BY order. The ordering used to plan the scans and joins
below stays as before, so an index that provides the old ordering
cheaply is not lost. In parallel plans the workers sort in either
ordering before the results are gathered.
The incremental patch changes two things, and adds tests.
> - The window ordering now follows enable_group_by_reordering, like the
> other reorderings. In v3 it was applied always.
Not only the window ordering. With the setting off, v4 still does
the direction-insensitive matching in truncate_useless_pathkeys()
and adjust_group_pathkeys_to_input(), so the d1/d2 query in
eager_aggregate.sql gets a different plan from master. The
incremental patch checks the setting there too, and adds that query
with the setting off to the test.
> 1. The missing operator error still happens with eager aggregation.
> Fixed. The check in v3 was only in group_keys_reorder_by_pathkeys(),
> but the partial aggregation goes through adjust_group_pathkeys_to_input(),
> which took the input's DESC pathkey without checking the operator. Now
> it stops there if the opfamily don't have the operator for that
> direction.
Here I take back my request from the last mail. The guard covers
only one path: with the same operator class, a merge join over the
backward index path still fails on v4 with "missing operator". On
the other hand, a btree operator class must provide all five
comparison operators (btree.sgml), and master already fails on such
a class with ORDER BY c DESC. So the incremental patch removes the
guard and its two tests, and the eager aggregation query from my
last mail fails again (it works with enable_group_by_reordering
off).
But that isn't mine to decide, so I'd like to know where the
consensus among committers is: should the planner keep working with
a btree operator class missing an operator, or can it be treated as
unsupported?
As for the tests, I wanted to know which parts of the patch the
regression tests actually pin, so I changed the patched code one
place at a time (mutation testing) and ran make check. Of 11 such
changes only one, dropping the window candidate in
get_useful_group_keys_orderings(), made a test fail. The
incremental patch adds tests that catch most of the others that
change a plan.
As for performance, these are from a release build, alternating
with master on a shared machine, so please read them as ranges.
master v4
your tb/ts query 74-86 ms 56-63 ms
ea/eb, hashagg off 181-192 ms 82-88 ms
43 queries from my last mail 42 change plans: 30 faster
(0.18-0.94x), 3 within 3%,
9 slower (1.05-2.28x)
planning time +2-6 us without windows (up to
+22 us on two join queries),
+3-8 us with windows
The window gains all come from 0002. The incremental patch doesn't
change plans with default settings, so these numbers still hold.
The nine slower ones get the same plans with 0001 alone; they are
mostly the Index Scan + Incremental Sort shape, the existing cost
estimate problem we agreed to leave for a separate patch. CREATE
STATISTICS (ndistinct) on the grouping columns fixes two of them
(2.2x and 1.25x). For three (1.1-1.3x) it only makes master pick
the same slower plan, and four (1.03-1.16x) stay, mostly because
uncorrelated Index Scans and Incremental Sort over many small groups
are costed too low.
One slower case is not in the matrix and comes from 0002: a window
query over 2M rows goes from HashAggregate + Sort (~220 ms) to Sort +
GroupAggregate (~900 ms), because x % 4 is estimated through x (2M
groups expected, 77k actual). CREATE STATISTICS ON (x % 4) fixes it;
ndistinct on the plain columns doesn't. With enable_hashagg off, the
window ordering can also put a low-cardinality key first in a large
sort, which runs 25-40% slower at the same cost, as the sort cost
doesn't depend on key order; master has the same weakness with
ORDER BY.
To sum up, the gains are broad and large, and I found no wrong
results. The losses are rare and come not from the patch's logic
but from existing limits of the planner's estimates and cost model:
group count estimates, a sort cost that ignores key order, and Index
Scans and Incremental Sorts costed too low. The patch does give
those limits more chances to show, since it offers more orderings,
and a badly wrong estimate can make a query several times slower at
default settings. Some cases are fixed by extended statistics; the
rest need cost model work, which I'd keep separate.
Based on the above, with the attached incremental patch, +1 from
me.
Best regards,
Henson
Re: [PATCH] Consider window functions when reordering GROUP BY items
Hi Henson,
Thanks for the thorough review and the +1. v5 is attached.
I took the enable_group_by_reordering checks in
count_common_leading_group_pathkeys() and adjust_group_pathkeys_to_input()
and all the new tests from your v4-0003, folded into 0001 and 0002. With
only 0001 applied, make check passes too.
For now I kept the operator guard and its tests. On master, such an
operator class fails only when the query asks for DESC, and then it is the
parser's "could not identify an ordering operator". With 0001 and without
the guard, your eager aggregation query fails with "missing operator"
although it has no DESC at all, and master runs it fine. So this failure
comes from 0001.
Could you share the merge join query that still fails on v4? I tried a
merge join over a backward index scan with the same operator class, and it
worked both on master and with v4-0003. If your query also fails on master,
the guard can't make things consistent and I'm fine dropping it. If not,
maybe it is better to check the operator once in
count_common_leading_group_pathkeys(), so that such pathkeys are not kept.
Either way, I agree it is the committers' decision.
Regards,
Thanks for the thorough review and the +1. v5 is attached.
I took the enable_group_by_reordering checks in
count_common_leading_group_pathkeys() and adjust_group_pathkeys_to_input()
and all the new tests from your v4-0003, folded into 0001 and 0002. With
only 0001 applied, make check passes too.
For now I kept the operator guard and its tests. On master, such an
operator class fails only when the query asks for DESC, and then it is the
parser's "could not identify an ordering operator". With 0001 and without
the guard, your eager aggregation query fails with "missing operator"
although it has no DESC at all, and master runs it fine. So this failure
comes from 0001.
Could you share the merge join query that still fails on v4? I tried a
merge join over a backward index scan with the same operator class, and it
worked both on master and with v4-0003. If your query also fails on master,
the guard can't make things consistent and I'm fine dropping it. If not,
maybe it is better to check the operator once in
count_common_leading_group_pathkeys(), so that such pathkeys are not kept.
Either way, I agree it is the committers' decision.
Regards,
Zhenglong Li
Re: [PATCH] Consider window functions when reordering GROUP BY items
От:
Henson Choi <assam258@gmail.com>
Дата:
Hi Zhenglong,
> Thanks for the thorough review and the +1. v5 is attached.
Thanks for v5. With both patches applied on master, make check
passes.
> Could you share the merge join query that still fails on v4? I tried a
> merge join over a backward index scan with the same operator class, and it
> worked both on master and with v4-0003.
Here it is. Both queries fail on v5 too with default settings, while
master returns 21 and 3 rows.
CREATE TYPE nh AS ENUM ('r', 'g', 'b');
CREATE FUNCTION nh_lt(nh, nh) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_lt';
CREATE FUNCTION nh_eq(nh, nh) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_eq';
CREATE FUNCTION nh_cmp(nh, nh) RETURNS int
LANGUAGE internal IMMUTABLE STRICT AS 'enum_cmp';
CREATE OPERATOR <<< (leftarg = nh, rightarg = nh, function = nh_lt);
CREATE OPERATOR === (leftarg = nh, rightarg = nh, function = nh_eq,
merges);
CREATE OPERATOR CLASS nh_ops DEFAULT FOR TYPE nh USING btree AS
OPERATOR 1 <<<, OPERATOR 3 ===, FUNCTION 1 nh_cmp(nh, nh);
CREATE TABLE tn (c nh, e int);
INSERT INTO tn SELECT (ARRAY['r', 'g', 'b'])[1 + i % 3]::nh, i % 7
FROM generate_series(1, 3000) i;
CREATE INDEX ON tn (c DESC) INCLUDE (e);
CREATE TABLE un (c nh);
INSERT INTO un SELECT (ARRAY['r', 'g', 'b'])[1 + i % 3]::nh
FROM generate_series(1, 30) i;
VACUUM ANALYZE tn, un;
SELECT t.c, t.e, count(*) FROM tn t JOIN un u ON t.c === u.c
GROUP BY t.c, t.e;
SELECT t.c, count(DISTINCT t.e) FROM tn t JOIN un u ON t.c === u.c
GROUP BY t.c;
It needs one more sort key after the index column, from GROUP BY or a
DISTINCT aggregate. The forward index scan is then kept as useful for
grouping, and the merge join fails sorting the other input by c DESC.
> If your query also fails on master,
> the guard can't make things consistent and I'm fine dropping it. If not,
> maybe it is better to check the operator once in
> count_common_leading_group_pathkeys(), so that such pathkeys are not kept.
Master runs it fine, so it's the latter. With that check on v5,
both queries above get master's plans and results. I have gone
through the overall flow of the code, and in broad terms it looks
right to me. I will take more time on the details, and keep looking
for regressions when the revised patch comes.
One thing so far: with partitionwise aggregation over 256 partitions
with indexes, planning time on v5 grows up to 2x over master, as the
orderings are considered for each partition. A table with 256
partitions holds a lot of data, though, so a few ms of planning should
not matter there.
> Either way, I agree it is the committers' decision.
Agreed.
Best regards,
Henson
> Thanks for the thorough review and the +1. v5 is attached.
Thanks for v5. With both patches applied on master, make check
passes.
> Could you share the merge join query that still fails on v4? I tried a
> merge join over a backward index scan with the same operator class, and it
> worked both on master and with v4-0003.
Here it is. Both queries fail on v5 too with default settings, while
master returns 21 and 3 rows.
CREATE TYPE nh AS ENUM ('r', 'g', 'b');
CREATE FUNCTION nh_lt(nh, nh) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_lt';
CREATE FUNCTION nh_eq(nh, nh) RETURNS bool
LANGUAGE internal IMMUTABLE STRICT AS 'enum_eq';
CREATE FUNCTION nh_cmp(nh, nh) RETURNS int
LANGUAGE internal IMMUTABLE STRICT AS 'enum_cmp';
CREATE OPERATOR <<< (leftarg = nh, rightarg = nh, function = nh_lt);
CREATE OPERATOR === (leftarg = nh, rightarg = nh, function = nh_eq,
merges);
CREATE OPERATOR CLASS nh_ops DEFAULT FOR TYPE nh USING btree AS
OPERATOR 1 <<<, OPERATOR 3 ===, FUNCTION 1 nh_cmp(nh, nh);
CREATE TABLE tn (c nh, e int);
INSERT INTO tn SELECT (ARRAY['r', 'g', 'b'])[1 + i % 3]::nh, i % 7
FROM generate_series(1, 3000) i;
CREATE INDEX ON tn (c DESC) INCLUDE (e);
CREATE TABLE un (c nh);
INSERT INTO un SELECT (ARRAY['r', 'g', 'b'])[1 + i % 3]::nh
FROM generate_series(1, 30) i;
VACUUM ANALYZE tn, un;
SELECT t.c, t.e, count(*) FROM tn t JOIN un u ON t.c === u.c
GROUP BY t.c, t.e;
SELECT t.c, count(DISTINCT t.e) FROM tn t JOIN un u ON t.c === u.c
GROUP BY t.c;
It needs one more sort key after the index column, from GROUP BY or a
DISTINCT aggregate. The forward index scan is then kept as useful for
grouping, and the merge join fails sorting the other input by c DESC.
> If your query also fails on master,
> the guard can't make things consistent and I'm fine dropping it. If not,
> maybe it is better to check the operator once in
> count_common_leading_group_pathkeys(), so that such pathkeys are not kept.
Master runs it fine, so it's the latter. With that check on v5,
both queries above get master's plans and results. I have gone
through the overall flow of the code, and in broad terms it looks
right to me. I will take more time on the details, and keep looking
for regressions when the revised patch comes.
One thing so far: with partitionwise aggregation over 256 partitions
with indexes, planning time on v5 grows up to 2x over master, as the
orderings are considered for each partition. A table with 256
partitions holds a lot of data, though, so a few ms of planning should
not matter there.
> Either way, I agree it is the committers' decision.
Agreed.
Best regards,
Henson
Re: [PATCH] Consider window functions when reordering GROUP BY items
Hi Henson,
> Master runs it fine, so it's the latter. With that check on v5, both
> queries above get master's plans and results.
Thanks for the repro. I could reproduce both queries failing on v5, and
also with only 0001 applied, while master returns 21 and 3 rows. v6 is
attached.
As you suggested, count_common_leading_group_pathkeys() now also requires
the sort operator, using pathkey_has_sort_operator(), for a pathkey that
matches a grouping key only when the direction is ignored. So the forward
index scan is no longer kept as useful for grouping, and both queries get
master's plans and results. Pathkeys that match a grouping key exactly
don't go through the check, so they cost nothing extra. I added your two
queries to the btg_color test in aggregates.sql; they fail without the
fix.
This also changes the plan of the eager aggregation test in
eager_aggregate.sql. It now scans the index backward with an incremental
sort, the same plan as on master, instead of scanning it forward and
doing a full sort.
About the other two guards, in group_keys_reorder_by_pathkeys() and
adjust_group_pathkeys_to_input(): I added a WARNING to both, and with
this fix make check reaches neither of them. I kept them for now, as I
can't be sure that no other path keeps such pathkeys, e.g. as useful for
merging. If you or a committer think they are dead code, I'm fine with
removing them.
> One thing so far: with partitionwise aggregation over 256 partitions
> with indexes, planning time on v5 grows up to 2x over master, as the
> orderings are considered for each partition. A table with 256
> partitions holds a lot of data, though, so a few ms of planning should
> not matter there.
I measured it too, with release builds of master (f03a0f87963) and v6,
on a table hash-partitioned into 256 partitions with indexes on (a, b)
and (b, c), and enable_partitionwise_aggregate on. Median planning
times in ms over 90 runs:
master v6 v6, reordering off
GROUP BY a, b (a is the partition key) 1.56 2.15 1.43
GROUP BY a, b ORDER BY a, b DESC 1.63 2.46 1.52
GROUP BY b, c (not partitionwise) 1.18 1.45 1.16
GROUP BY a, b, window on (b, a DESC) 1.58 2.86 1.46
GROUP BY b, c, window on (c, b DESC) 1.10 1.48 1.10
So it's 1.2x to 1.8x, or 0.3 to 1.3 ms in total, in line with what you
saw, and with enable_group_by_reordering off v6 plans as fast as master.
With only 2000 rows per partition these queries already take 20 to
70 ms to execute, so I agree it should not matter.
Regards,
Zhenglong Li
> Master runs it fine, so it's the latter. With that check on v5, both
> queries above get master's plans and results.
Thanks for the repro. I could reproduce both queries failing on v5, and
also with only 0001 applied, while master returns 21 and 3 rows. v6 is
attached.
As you suggested, count_common_leading_group_pathkeys() now also requires
the sort operator, using pathkey_has_sort_operator(), for a pathkey that
matches a grouping key only when the direction is ignored. So the forward
index scan is no longer kept as useful for grouping, and both queries get
master's plans and results. Pathkeys that match a grouping key exactly
don't go through the check, so they cost nothing extra. I added your two
queries to the btg_color test in aggregates.sql; they fail without the
fix.
This also changes the plan of the eager aggregation test in
eager_aggregate.sql. It now scans the index backward with an incremental
sort, the same plan as on master, instead of scanning it forward and
doing a full sort.
About the other two guards, in group_keys_reorder_by_pathkeys() and
adjust_group_pathkeys_to_input(): I added a WARNING to both, and with
this fix make check reaches neither of them. I kept them for now, as I
can't be sure that no other path keeps such pathkeys, e.g. as useful for
merging. If you or a committer think they are dead code, I'm fine with
removing them.
> One thing so far: with partitionwise aggregation over 256 partitions
> with indexes, planning time on v5 grows up to 2x over master, as the
> orderings are considered for each partition. A table with 256
> partitions holds a lot of data, though, so a few ms of planning should
> not matter there.
I measured it too, with release builds of master (f03a0f87963) and v6,
on a table hash-partitioned into 256 partitions with indexes on (a, b)
and (b, c), and enable_partitionwise_aggregate on. Median planning
times in ms over 90 runs:
master v6 v6, reordering off
GROUP BY a, b (a is the partition key) 1.56 2.15 1.43
GROUP BY a, b ORDER BY a, b DESC 1.63 2.46 1.52
GROUP BY b, c (not partitionwise) 1.18 1.45 1.16
GROUP BY a, b, window on (b, a DESC) 1.58 2.86 1.46
GROUP BY b, c, window on (c, b DESC) 1.10 1.48 1.10
So it's 1.2x to 1.8x, or 0.3 to 1.3 ms in total, in line with what you
saw, and with enable_group_by_reordering off v6 plans as fast as master.
With only 2000 rows per partition these queries already take 20 to
70 ms to execute, so I agree it should not matter.
Regards,
Zhenglong Li
Re: [PATCH] Consider window functions when reordering GROUP BY items
Hi Zhenglong,
> As you suggested, count_common_leading_group_pathkeys() now also requires
> the sort operator, using pathkey_has_sort_operator(), for a pathkey that
> matches a grouping key only when the direction is ignored.
Thanks for v6. I read it again in planning order: where a sorted
path is kept, how eager aggregation below the join uses it, which
GROUP BY orders become candidates, which orders the parallel paths
are sorted in, and what turning the GUC off does. Please correct
me if I got any of it wrong.
truncate_useless_pathkeys():
- A path whose leading keys are GROUP BY columns, in any order,
sorted in the other direction now counts as useful, so it is no
longer thrown away before grouping. This only decides whether
the path is kept; it does not change its order.
- It counts only if the operator family has the sort operator for
that direction, so both repro queries get master's plans and
results.
generate_grouped_paths(), for eager aggregation:
- No candidates are made here. For each input path, the leading
grouping keys that the input is sorted on, in either direction,
are changed to the input's direction; the key order is kept.
- This is fine, as the partial aggregation here compares the keys
only for equality, and the grouping step above the join still
provides the final GROUP BY and its order.
get_useful_group_keys_orderings():
- Existing candidates: the original order, which follows ORDER BY,
and the input path's order. The latter is now also made when
the direction differs: the GROUP BY keys are changed to the
input's direction, and it stops where they can't be sorted that
way.
- New candidate: the GROUP BY keys reordered to the first window's
PARTITION BY and ORDER BY, unless another candidate is already
the same. It is kept even when only some of the GROUP BY keys
match the window.
gather_grouping_paths():
- Existing order: the original order. Parallel paths, such as
partial aggregates, are sorted in it before Gather Merge.
- Added order: the same reordering to the first window, tried as
well as the original one. So the workers do the sort for the
window below Gather Merge, instead of the leader above it.
Turning enable_group_by_reordering off turns all of this off:
- truncate_useless_pathkeys(): a path sorted in the opposite
direction is not kept for GROUP BY.
- generate_grouped_paths(): it sorts only in the original direction.
- get_useful_group_keys_orderings(): only the original order is
offered.
- gather_grouping_paths(): no window order is added, so parallel
paths are sorted only in the original order.
So the plans are those of master with the GUC off, and planning is
no slower than on master, as the last column of your table shows.
With it on, as I said in my last mail, the extra planning time should
not matter for a table with that many partitions.
> About the other two guards, in group_keys_reorder_by_pathkeys() and
> adjust_group_pathkeys_to_input(): I added a WARNING to both, and with
> this fix make check reaches neither of them. I kept them for now, as I
> can't be sure that no other path keeps such pathkeys, e.g. as useful for
> merging.
I don't think they are dead code. I turned both into Asserts on a
cassert build, and each fails on one of the attached queries, while
v6 as posted runs them fine:
- group_keys_reorder_by_pathkeys(): a cross-type operator family
where the window's ORDER BY type has the reverse operator but
the GROUP BY type doesn't, through the window candidate.
- adjust_group_pathkeys_to_input(): eager aggregation with an
operator class that has only = and >, where a forward index
scan is kept as useful for merging.
So I'd keep them as runtime checks.
The code looks good to me. For the docs, the description of
enable_group_by_reordering in config.sgml still talks only about the
order of a child node's keys, though the GUC now also covers their
direction and the window's order. How about updating it along these
lines?
Controls if the query planner will produce a plan which will
provide GROUP BY keys sorted in the order of keys of a child
node of the plan, such as an index scan, in either sort
direction, or in the order required by window functions.
Thank you for the careful work on it.
Best regards,
Henson
> As you suggested, count_common_leading_group_pathkeys() now also requires
> the sort operator, using pathkey_has_sort_operator(), for a pathkey that
> matches a grouping key only when the direction is ignored.
Thanks for v6. I read it again in planning order: where a sorted
path is kept, how eager aggregation below the join uses it, which
GROUP BY orders become candidates, which orders the parallel paths
are sorted in, and what turning the GUC off does. Please correct
me if I got any of it wrong.
truncate_useless_pathkeys():
- A path whose leading keys are GROUP BY columns, in any order,
sorted in the other direction now counts as useful, so it is no
longer thrown away before grouping. This only decides whether
the path is kept; it does not change its order.
- It counts only if the operator family has the sort operator for
that direction, so both repro queries get master's plans and
results.
generate_grouped_paths(), for eager aggregation:
- No candidates are made here. For each input path, the leading
grouping keys that the input is sorted on, in either direction,
are changed to the input's direction; the key order is kept.
- This is fine, as the partial aggregation here compares the keys
only for equality, and the grouping step above the join still
provides the final GROUP BY and its order.
get_useful_group_keys_orderings():
- Existing candidates: the original order, which follows ORDER BY,
and the input path's order. The latter is now also made when
the direction differs: the GROUP BY keys are changed to the
input's direction, and it stops where they can't be sorted that
way.
- New candidate: the GROUP BY keys reordered to the first window's
PARTITION BY and ORDER BY, unless another candidate is already
the same. It is kept even when only some of the GROUP BY keys
match the window.
gather_grouping_paths():
- Existing order: the original order. Parallel paths, such as
partial aggregates, are sorted in it before Gather Merge.
- Added order: the same reordering to the first window, tried as
well as the original one. So the workers do the sort for the
window below Gather Merge, instead of the leader above it.
Turning enable_group_by_reordering off turns all of this off:
- truncate_useless_pathkeys(): a path sorted in the opposite
direction is not kept for GROUP BY.
- generate_grouped_paths(): it sorts only in the original direction.
- get_useful_group_keys_orderings(): only the original order is
offered.
- gather_grouping_paths(): no window order is added, so parallel
paths are sorted only in the original order.
So the plans are those of master with the GUC off, and planning is
no slower than on master, as the last column of your table shows.
With it on, as I said in my last mail, the extra planning time should
not matter for a table with that many partitions.
> About the other two guards, in group_keys_reorder_by_pathkeys() and
> adjust_group_pathkeys_to_input(): I added a WARNING to both, and with
> this fix make check reaches neither of them. I kept them for now, as I
> can't be sure that no other path keeps such pathkeys, e.g. as useful for
> merging.
I don't think they are dead code. I turned both into Asserts on a
cassert build, and each fails on one of the attached queries, while
v6 as posted runs them fine:
- group_keys_reorder_by_pathkeys(): a cross-type operator family
where the window's ORDER BY type has the reverse operator but
the GROUP BY type doesn't, through the window candidate.
- adjust_group_pathkeys_to_input(): eager aggregation with an
operator class that has only = and >, where a forward index
scan is kept as useful for merging.
So I'd keep them as runtime checks.
The code looks good to me. For the docs, the description of
enable_group_by_reordering in config.sgml still talks only about the
order of a child node's keys, though the GUC now also covers their
direction and the window's order. How about updating it along these
lines?
Controls if the query planner will produce a plan which will
provide GROUP BY keys sorted in the order of keys of a child
node of the plan, such as an index scan, in either sort
direction, or in the order required by window functions.
Thank you for the careful work on it.
Best regards,
Henson