avantgardnerio commented on code in PR #17347:
URL: https://github.com/apache/datafusion/pull/17347#discussion_r2427604264


##########
datafusion/physical-optimizer/src/limit_pushdown_past_window.rs:
##########
@@ -0,0 +1,141 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use crate::PhysicalOptimizerRule;
+use datafusion_common::config::ConfigOptions;
+use datafusion_common::tree_node::{Transformed, TreeNode};
+use datafusion_common::ScalarValue;
+use datafusion_expr::{WindowFrameBound, WindowFrameUnits};
+use datafusion_physical_plan::execution_plan::CardinalityEffect;
+use datafusion_physical_plan::limit::GlobalLimitExec;
+use datafusion_physical_plan::sorts::sort::SortExec;
+use datafusion_physical_plan::windows::BoundedWindowAggExec;
+use datafusion_physical_plan::ExecutionPlan;
+use std::cmp;
+use std::sync::Arc;
+
+/// This rule inspects [`ExecutionPlan`]'s attempting to find fetch limits 
that were not pushed
+/// down by `LimitPushdown` because [BoundedWindowAggExec]s were "in the way". 
If the window is
+/// bounded by [WindowFrameUnits::Rows] then we calculate the adjustment 
needed to grow the limit
+/// and continue pushdown.
+#[derive(Default, Clone, Debug)]
+pub struct LimitPushPastWindows;
+
+impl LimitPushPastWindows {
+    pub fn new() -> Self {
+        Self
+    }
+}
+
+impl PhysicalOptimizerRule for LimitPushPastWindows {
+    fn optimize(
+        &self,
+        original: Arc<dyn ExecutionPlan>,
+        config: &ConfigOptions,
+    ) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
+        if !config.optimizer.enable_window_limits {
+            return Ok(original);
+        }
+        let mut latest_limit: Option<usize> = None;
+        let mut latest_max = 0;
+        let result = original.transform_down(|node| {
+            // helper closure to DRY out most the early return cases
+            let mut reset = |node,
+                             max: &mut usize|
+             -> datafusion_common::Result<
+                Transformed<Arc<dyn ExecutionPlan>>,
+            > {
+                latest_limit = None;
+                *max = 0;
+                Ok(Transformed::no(node))
+            };
+
+            // traversing sides of joins will require more thought
+            if node.children().len() > 1 {
+                return reset(node, &mut latest_max);
+            }
+
+            // grab the latest limit we see
+            if let Some(limit) = 
node.as_any().downcast_ref::<GlobalLimitExec>() {
+                latest_limit = limit.fetch().map(|fetch| fetch + limit.skip());
+                latest_max = 0;
+                return Ok(Transformed::no(node));
+            }
+
+            // grow the limit if we hit a window function
+            if let Some(window) = 
node.as_any().downcast_ref::<BoundedWindowAggExec>() {
+                for expr in window.window_expr().iter() {
+                    let frame = expr.get_window_frame();
+                    if frame.units != WindowFrameUnits::Rows {

Review Comment:
   I tried this and I think it's unsafe:
   ```
   1. query result mismatch:
   [SQL] SELECT
    SUM(c1) OVER (ORDER BY c2 DESC) as summation1
    FROM null_cases
    LIMIT 5;
   [Diff] (-expected|+actual)
   -   962
   -   962
   -   962
   -   962
   -   962
   +   263
   +   263
   +   263
   +   263
   +   263
   ```
   and
   ```
   [Diff] (-expected|+actual)
       logical_plan
       01)Projection: sum(null_cases.c1) ORDER BY [null_cases.c2 DESC NULLS 
FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW AS summation1
       02)--Limit: skip=0, fetch=5
       03)----WindowAggr: windowExpr=[[sum(null_cases.c1) ORDER BY 
[null_cases.c2 DESC NULLS FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT 
ROW]]
       04)------TableScan: null_cases projection=[c1, c2]
       physical_plan
       01)ProjectionExec: expr=[sum(null_cases.c1) ORDER BY [null_cases.c2 DESC 
NULLS FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW@2 as summation1]
       02)--GlobalLimitExec: skip=0, fetch=5
       03)----BoundedWindowAggExec: wdw=[sum(null_cases.c1) ORDER BY 
[null_cases.c2 DESC NULLS FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT 
ROW: Field { name: "sum(null_cases.c1) ORDER BY [null_cases.c2 DESC NULLS 
FIRST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW", data_type: Int64, 
nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }, frame: 
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW], mode=[Sorted]
   -   04)------SortExec: expr=[c2@1 DESC], preserve_partitioning=[false]
   +   04)------SortExec: TopK(fetch=5), expr=[c2@1 DESC], 
preserve_partitioning=[false]
       05)--------DataSourceExec: file_groups={1 group: 
[[WORKSPACE_ROOT/datafusion/core/tests/data/null_cases.csv]]}, projection=[c1, 
c2], file_type=csv, has_header=true
       ```
   I think this is failing because there are multiple entries with the same 
value, so it needs more than the limit.



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