jayzhan211 commented on code in PR #27430:
URL: https://github.com/apache/datafusion/pull/27430#discussion_r4655915727
##########
datafusion/physical-optimizer/src/topk_aggregation.rs:
##########
@@ -131,21 +131,23 @@ impl TopKAggregation {
if let Some(aggr) = plan.downcast_ref::<AggregateExec>() {
match aggr
.clone()
- .try_optimize_topk(limit, &sort_col_name, sort_options)
+ .try_optimize_topk(limit, sort_col.name(), sort_options)
{
None => cardinality_preserved = false,
Some(aggr) => return
Ok(Transformed::yes(Arc::new(aggr.data))),
}
} else if let Some(proj) = plan.downcast_ref::<ProjectionExec>() {
- // track renames due to successive projections
- for proj_expr in proj.expr() {
- let Some(src_col) =
proj_expr.expr.downcast_ref::<Column>() else {
- continue;
- };
- if proj_expr.alias == sort_col_name {
- sort_col_name = src_col.name().to_string();
- }
- }
+ let Some(src_col) = proj
+ .expr()
+ .get(sort_col.index())
+ .and_then(|e| e.expr.downcast_ref::<Column>())
+ else {
+ // A computed expression can produce values that
aggregation did not see.
+ // We cannot apply the topk optimization then
Review Comment:
Optional cleanup: the values aren't the problem here. The sort orders by the
computed value, and that order can differ from the aggregate's, so the comment
could say that:
```suggestion
// The sort orders by the computed value, whose order
can differ
// from the aggregate's (`-min(x)` reverses it).
```
##########
datafusion/sqllogictest/test_files/aggregates_topk.slt:
##########
@@ -886,3 +886,40 @@ GROUP BY k ORDER BY MAX(v) DESC NULLS LAST LIMIT 1;
statement ok
set datafusion.execution.target_partitions = 4;
+
+# A computed column that reuses the aggregate's name must not get a TopK limit;
+# See: https://github.com/apache/datafusion/issues/27195
+statement ok
+CREATE TABLE topk_computed_alias (g BIGINT, x BIGINT) AS VALUES (1, 100), (2,
90), (3, 10), (4, 5);
+
+query II
+SELECT g, -"min(topk_computed_alias.x)" AS "min(topk_computed_alias.x)"
+FROM (SELECT g, min(x) FROM topk_computed_alias GROUP BY g)
+ORDER BY "min(topk_computed_alias.x)"
+LIMIT 2;
+----
+1 -100
+2 -90
+
+query TT
+EXPLAIN SELECT g, -"min(topk_computed_alias.x)" AS "min(topk_computed_alias.x)"
+FROM (SELECT g, min(x) FROM topk_computed_alias GROUP BY g)
+ORDER BY "min(topk_computed_alias.x)"
+LIMIT 2;
+----
+logical_plan
+01)Sort: min(topk_computed_alias.x) ASC NULLS LAST, fetch=2
+02)--Projection: topk_computed_alias.g, (- min(topk_computed_alias.x)) AS
min(topk_computed_alias.x)
+03)----Aggregate: groupBy=[[topk_computed_alias.g]],
aggr=[[min(topk_computed_alias.x)]]
+04)------TableScan: topk_computed_alias projection=[g, x]
+physical_plan
+01)SortPreservingMergeExec: [min(topk_computed_alias.x)@1 ASC NULLS LAST],
fetch=2
+02)--SortExec: TopK(fetch=2), expr=[min(topk_computed_alias.x)@1 ASC NULLS
LAST], preserve_partitioning=[true]
+03)----ProjectionExec: expr=[g@0 as g, (- min(topk_computed_alias.x)@1) as
min(topk_computed_alias.x)]
+04)------AggregateExec: mode=FinalPartitioned, gby=[g@0 as g],
aggr=[min(topk_computed_alias.x)]
+05)--------RepartitionExec: partitioning=Hash([g@0], 4), input_partitions=1
+06)----------AggregateExec: mode=Partial, gby=[g@0 as g],
aggr=[min(topk_computed_alias.x)]
+07)------------DataSourceExec: partitions=1, partition_sizes=[1]
+
+statement ok
+DROP TABLE topk_computed_alias;
Review Comment:
Optional: this fix also covers `SELECT DISTINCT`, where the reused name is a
plain column name, so it's the shape users are most likely to hit. On main this
query returns `-3, -4`. Could you add it?
```suggestion
# The same bug for SELECT DISTINCT, where the reused name is a plain column
name
query I
SELECT -g AS g FROM (SELECT DISTINCT g FROM topk_computed_alias)
ORDER BY g DESC
LIMIT 2;
----
-1
-2
statement ok
DROP TABLE topk_computed_alias;
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]