jayzhan211 commented on code in PR #27532:
URL: https://github.com/apache/datafusion/pull/27532#discussion_r4666500856
##########
datafusion/physical-optimizer/src/limit_pushdown_past_window.rs:
##########
@@ -175,12 +210,21 @@ fn apply_limit(
// fetch bounds every partition below it too: start the next chain from it.
// This sits before the early return below on purpose -- with no limit in
hand
// the merge is left alone, but its own fetch is still a bound to carry
down.
- if node.is::<SortPreservingMergeExec>() {
- ctx.reset_limit(fetch.or_else(|| node.fetch()));
+ if let Some(merge) = node.downcast_ref::<SortPreservingMergeExec>() {
+ ctx.reset_limit(fetch.or_else(|| node.fetch()),
Some(merge_ordering(merge)));
}
let Some(fetch) = fetch else {
return Some(Transformed::no(Arc::clone(node)));
};
+ // A node with more than one output partition keeps the globally first
+ // `fetch` rows, not the first rows of each partition the window reads. An
+ // ordered merge above the window makes it a bound again: a row the window
+ // got wrong lost to `fetch` rows that all reach the merge before it.
+ if node.output_partitioning().partition_count() > 1
+ && !(partitions_separated && keeps_partitions_whole(node,
narrowest_partition_by))
+ {
Review Comment:
@cool9850311 the window already requires `KeyPartitioned(PARTITION BY)`, so
every window partition is whole in one stream. `keeps_partitions_whole` checks
a narrower version of that rule, and it drops the TopK on valid plans where
`main` keeps it: a constant key (the sort drops `a`, so the hash isn't a prefix
of the sort anymore), and a subset hash:
```sql
SET datafusion.execution.target_partitions = 4;
SET datafusion.optimizer.repartition_file_scans = false;
CREATE TABLE t1 (a INT, b INT, c INT) AS VALUES (1,1,1),(1,2,2),(2,1,3);
CREATE TABLE t2 (a INT, b INT, c INT) AS VALUES (1,1,6);
EXPLAIN SELECT a, b, c, row_number() OVER (PARTITION BY a, b ORDER BY c ROWS
UNBOUNDED PRECEDING) rn
FROM (SELECT * FROM t1 UNION ALL SELECT * FROM t2) WHERE a = 1 ORDER BY a, b
LIMIT 3;
EXPLAIN SELECT b, m, row_number() OVER (PARTITION BY m, b ORDER BY m ROWS
UNBOUNDED PRECEDING) rn
FROM (SELECT b, max(c) m FROM (SELECT * FROM t1 UNION ALL SELECT * FROM t2)
GROUP BY b) ORDER BY m, b LIMIT 3;
```
The three unit tests behind this check (round robin, hash on `b`, hash on
`a, b`) build plans that `SanityCheckPlan` rejects. The constant filter in
`merge_ordering` only makes the check stricter, and no test fails without it.
Could you drop `keeps_partitions_whole`, `partition_by_width`,
`narrowest_partition_by`, the constant filter and those three tests, and add
the two queries above as `EXPLAIN` tests? With that and the window carry, I get
the unit tests, `window_limits.slt` and clippy green, and a randomized subset
check returns 0 wrong rows out of 180 per shape.
```suggestion
if node.output_partitioning().partition_count() > 1 &&
!partitions_separated {
```
<details>
<summary>The rest of the change, besides deleting the two functions</summary>
```diff
- /// The narrowest `PARTITION BY` over the windows crossed so far.
- pub narrowest_partition_by: usize,
@@
- self.narrowest_partition_by = usize::MAX;
@@
ctx.partitions_separated &= separates_partitions(&node,
&ctx);
- ctx.narrowest_partition_by =
-
ctx.narrowest_partition_by.min(partition_by_width(&node));
@@
partitions_separated,
- narrowest_partition_by,
..
@@
fn merge_ordering(merge: &SortPreservingMergeExec) -> Vec<Arc<dyn
PhysicalExpr>> {
- let input = merge.input().equivalence_properties();
merge
.expr()
.iter()
- .filter(|sort_expr|
input.is_expr_constant(&sort_expr.expr).is_none())
.map(|sort_expr| Arc::clone(&sort_expr.expr))
.collect()
}
```
</details>
##########
datafusion/physical-optimizer/src/limit_pushdown_past_window.rs:
##########
@@ -190,21 +234,105 @@ fn get_limit(node: &Arc<dyn ExecutionPlan>, ctx: &mut
TraverseState) -> bool {
// In distributed execution, GlobalLimitExec becomes LocalLimitExec
// per partition. Handle it the same way (LocalLimitExec has no skip).
if let Some(limit) = RowBound::of_limit_node(node) {
- ctx.reset_limit(limit.input_rows());
+ ctx.reset_limit(limit.input_rows(), None);
return true;
}
- if let Some(limit) = node.downcast_ref::<SortPreservingMergeExec>() {
- ctx.reset_limit(limit.fetch());
+ if let Some(merge) = node.downcast_ref::<SortPreservingMergeExec>() {
+ ctx.reset_limit(merge.fetch(), Some(merge_ordering(merge)));
return true;
}
false
}
+/// Whether every window partition `node` reads is whole within one of its
+/// output partitions, so that a row's own earlier rows share its partition.
+fn keeps_partitions_whole(node: &Arc<dyn ExecutionPlan>, rank_needed: usize)
-> bool {
+ let Partitioning::Hash(hash_exprs, _) = node.output_partitioning() else {
+ return false;
+ };
+ node.downcast_ref::<SortExec>().is_some_and(|sort| {
+ hash_exprs.len() <= rank_needed
+ && hash_exprs
+ .iter()
+ .zip(sort.expr().iter())
+ .all(|(hashed, sorted)| hashed.eq(&sorted.expr))
+ })
+}
+
+/// The expressions of `merge`'s ordering that order its rows: one that is
+/// constant in its input orders nothing.
+fn merge_ordering(merge: &SortPreservingMergeExec) -> Vec<Arc<dyn
PhysicalExpr>> {
+ let input = merge.input().equivalence_properties();
+ merge
+ .expr()
+ .iter()
+ .filter(|sort_expr| input.is_expr_constant(&sort_expr.expr).is_none())
+ .map(|sort_expr| Arc::clone(&sort_expr.expr))
+ .collect()
+}
+
+/// Whether the ordering in hand sorts `node`'s rows into the groups its
windows
+/// read: every `PARTITION BY` expression has to be one of the ordering's own.
A
+/// window with no `PARTITION BY` reads one group that no ordering separates.
+fn separates_partitions(node: &Arc<dyn ExecutionPlan>, ctx: &TraverseState) ->
bool {
+ let (Some(exprs), Some(window)) = (
+ ctx.merge_exprs.as_ref(),
+ node.downcast_ref::<BoundedWindowAggExec>(),
+ ) else {
+ return false;
+ };
+ !window.window_expr().is_empty()
+ && window.window_expr().iter().all(|window_expr| {
+ !window_expr.partition_by().is_empty()
+ && window_expr
+ .partition_by()
+ .iter()
+ .all(|key| exprs.iter().any(|expr| expr.eq(key)))
+ })
+}
+
+/// The narrowest `PARTITION BY` of `node`'s window expressions, or
`usize::MAX`
+/// for anything else -- [`separates_partitions`] blocks those on its own.
+fn partition_by_width(node: &Arc<dyn ExecutionPlan>) -> usize {
+ let Some(window) = node.downcast_ref::<BoundedWindowAggExec>() else {
+ return usize::MAX;
+ };
+ window
+ .window_expr()
+ .iter()
+ .map(|expr| expr.partition_by().len())
+ .min()
+ .unwrap_or(usize::MAX)
+}
+
+/// Carry the merge's ordering from `node`'s output into its input's expression
+/// space: a projection moves and renames columns, so the ordering is rewritten
+/// through it, and a node that changes the schema any other way ends the
carry.
+fn carry_down(node: &Arc<dyn ExecutionPlan>, ctx: &mut TraverseState) {
+ let Some(exprs) = ctx.merge_exprs.take() else {
+ return;
+ };
+ let Some(child) = node.children().into_iter().next() else {
+ return;
+ };
+ ctx.merge_exprs = if let Some(projection) =
node.downcast_ref::<ProjectionExec>() {
+ exprs
+ .iter()
+ .map(|expr| projection.projection_expr().unproject_expr(expr).ok())
+ .collect()
+ } else if node.schema() == child.schema() {
+ Some(exprs)
+ } else {
+ None
+ };
Review Comment:
@cool9850311 the carry stops at every window, because a window's schema
differs from its input's. So two stacked windows always lose the fetch, even
when the `ORDER BY` covers both, and `main` keeps `TopK(fetch=3)` there:
```sql
SET datafusion.execution.target_partitions = 4;
SET datafusion.optimizer.repartition_file_scans = false;
CREATE TABLE t1 (a INT, b INT, c INT) AS VALUES (1,1,1),(1,2,2),(2,1,3);
CREATE TABLE t2 (a INT, b INT, c INT) AS VALUES (1,1,6);
EXPLAIN SELECT a, b, c,
row_number() OVER (PARTITION BY a ORDER BY b ROWS UNBOUNDED PRECEDING) r1,
row_number() OVER (PARTITION BY a ORDER BY b, c ROWS UNBOUNDED PRECEDING)
r2
FROM (SELECT * FROM t1 UNION ALL SELECT * FROM t2) ORDER BY a LIMIT 3;
```
A window appends its columns after its input's, so the ordering can pass
through it. Could you add this, plus the query above as an `EXPLAIN` test? It
also needs `use datafusion_physical_expr::utils::collect_columns;`.
```suggestion
} else if node.schema() == child.schema() {
Some(exprs)
} else if node.is::<BoundedWindowAggExec>() {
// A window appends its columns after its input's, so an expression
// over input columns means the same on both sides.
let input_columns = child.schema().fields().len();
exprs
.into_iter()
.map(|expr| {
collect_columns(&expr)
.iter()
.all(|column| column.index() < input_columns)
.then_some(expr)
})
.collect()
} else {
None
};
```
--
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]