jayzhan211 commented on code in PR #27532:
URL: https://github.com/apache/datafusion/pull/27532#discussion_r4708403352


##########
datafusion/physical-optimizer/src/limit_pushdown_past_window.rs:
##########
@@ -190,21 +227,84 @@ 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
 }
 
+fn merge_ordering(merge: &SortPreservingMergeExec) -> Vec<Arc<dyn 
PhysicalExpr>> {
+    merge
+        .expr()
+        .iter()
+        .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 {

Review Comment:
   @cool9850311 thanks for the quick turnaround. I need to correct my own 
earlier ask: requiring every `PARTITION BY` expression in the merge's ordering 
is stricter than the argument needs, and it drops `TopK(fetch=3)` on two plans 
`main` gets right (0 wrong rows in 240 randomized runs). Those plans are 
stacked windows `PARTITION BY a` over `PARTITION BY a, b` under `ORDER BY a`, 
and `WHERE a = 1 … PARTITION BY a, b … ORDER BY b`. The argument only needs 
every row that ties with `r` on the merge's ordering to sit in `r`'s 
merge-input partition, and that holds when every hash key of the merge's input 
is in the ordering or is a constant. Checked once at the merge, that also 
removes `carry_down`, `separates_partitions` and `merge_ordering` (−85/+37). 
With it, the unit tests, `window_limits.slt` (including all six repros) and 
clippy pass, and the randomized subset check finds 0 wrong rows on every shape. 
Could you apply it and add the two EXPLAIN tests below? Both fail at this head
 .
   
   <details>
   <summary>The change</summary>
   
   ```diff
   -use datafusion_physical_expr::PhysicalExpr;
   -use datafusion_physical_expr::utils::collect_columns;
   -use datafusion_physical_plan::projection::ProjectionExec;
   +use datafusion_physical_expr::{AcrossPartitions, physical_exprs_contains};
    use datafusion_physical_plan::sorts::sort::SortExec;
    use 
datafusion_physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
   -use datafusion_physical_plan::windows::BoundedWindowAggExec;
    use datafusion_physical_plan::{
   -    ExecutionPlan, ExecutionPlanProperties, LimitBehavior, WindowLookahead,
   +    ExecutionPlan, ExecutionPlanProperties, LimitBehavior, Partitioning, 
WindowLookahead,
    };
   @@ struct TraverseState
   -    /// The ordering of the merge the limit came from, in the expression 
space of
   -    /// the node being visited.
   -    pub merge_exprs: Option<Vec<Arc<dyn PhysicalExpr>>>,
   -    /// Whether it separates the groups of every window crossed so far.
   -    pub partitions_separated: bool,
   +    /// Whether rows that tie on the ordering of the merge the limit came 
from
   +    /// share one of its input partitions.
   +    pub ties_in_one_partition: bool,
   @@ fn reset_limit
   -    pub fn reset_limit(
   -        &mut self,
   -        limit: Option<usize>,
   -        merge_exprs: Option<Vec<Arc<dyn PhysicalExpr>>>,
   -    ) {
   +    pub fn reset_limit(&mut self, limit: Option<usize>, 
ties_in_one_partition: bool) {
            self.limit = limit;
            self.lookahead = 0;
            self.phase = Phase::FindOrGrow;
   -        self.partitions_separated = merge_exprs.is_some();
   -        self.merge_exprs = merge_exprs;
   +        self.ties_in_one_partition = ties_in_one_partition;
   @@ fn optimize
                    if !grow_limit(lookahead, &mut ctx) {
                        return reset(node, &mut ctx);
                    }
   -                ctx.partitions_separated &= separates_partitions(&node, 
&ctx);
   -                carry_down(&node, &mut ctx);
                    return Ok(Transformed::no(node));
   @@
                if node.output_ordering().is_none() {
   -                ctx.merge_exprs = None;
   -                ctx.partitions_separated = false;
   +                ctx.ties_in_one_partition = false;
                }
   -            carry_down(&node, &mut ctx);
   @@ fn apply_limit
   -        partitions_separated,
   +        ties_in_one_partition,
   @@
   -        ctx.reset_limit(fetch.or_else(|| node.fetch()), 
Some(merge_ordering(merge)));
   +        ctx.reset_limit(
   +            fetch.or_else(|| node.fetch()),
   +            ties_stay_in_one_partition(merge),
   +        );
   @@
   -    if node.output_partitioning().partition_count() > 1 && 
!partitions_separated {
   +    if node.output_partitioning().partition_count() > 1 && 
!ties_in_one_partition {
   @@ fn get_limit
   -        ctx.reset_limit(limit.input_rows(), None);
   +        ctx.reset_limit(limit.input_rows(), false);
   @@
   -        ctx.reset_limit(merge.fetch(), Some(merge_ordering(merge)));
   +        ctx.reset_limit(merge.fetch(), ties_stay_in_one_partition(merge));
   ```
   
   Then replace `merge_ordering`, `separates_partitions` and `carry_down` with:
   
   ```rs
   /// Whether rows that tie on `merge`'s ordering always share one of its input
   /// partitions. A fetch on a sort below that keeps several partitions then 
drops
   /// only rows behind at least `fetch` rows that reach the merge before them.
   fn ties_stay_in_one_partition(merge: &SortPreservingMergeExec) -> bool {
       let input = merge.input();
       let Partitioning::Hash(keys, _) = input.output_partitioning() else {
           return false;
       };
       let eq_properties = input.equivalence_properties();
       let eq_group = eq_properties.eq_group();
       let ordering = merge
           .expr()
           .iter()
           .map(|sort_expr| 
eq_group.normalize_expr(Arc::clone(&sort_expr.expr)))
           .collect::<Vec<_>>();
       keys.iter().all(|key| {
           physical_exprs_contains(&ordering, 
&eq_group.normalize_expr(Arc::clone(key)))
               || matches!(
                   eq_properties.is_expr_constant(key),
                   Some(AcrossPartitions::Uniform(_))
               )
       })
   }
   ```
   
   The doc comments on 
`a_merge_ordered_by_an_alias_above_a_projection_takes_the_fetch` and 
`a_merge_over_stacked_windows_takes_the_fetch` describe the carry and would 
need a reword.
   
   </details>
   
   <details>
   <summary>Two EXPLAIN tests for window_limits.slt, before the final RESETs 
(both keep the TopK, as on main)</summary>
   
   ```
   query TT
   EXPLAIN
   SELECT a, b, c,
     row_number() OVER (PARTITION BY a ORDER BY b, c ROWS UNBOUNDED PRECEDING) 
AS r1,
     row_number() OVER (PARTITION BY a, b ORDER BY c ROWS UNBOUNDED PRECEDING) 
AS r2
   FROM (SELECT * FROM w27457_covered UNION ALL SELECT * FROM 
w27457_covered_late)
   ORDER BY a LIMIT 3;
   ----
   
   query TT
   EXPLAIN
   SELECT a, b, c, row_number() OVER (PARTITION BY a, b ORDER BY c ROWS 
UNBOUNDED PRECEDING) AS rn
   FROM (SELECT * FROM w27457_covered UNION ALL SELECT * FROM 
w27457_covered_late)
   WHERE a = 1 ORDER BY b LIMIT 3;
   ----
   ```
   
   `--complete` fills in plans with `SortExec: TopK(fetch=3)` below the windows.
   
   </details>



-- 
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]

Reply via email to