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


##########
datafusion/physical-optimizer/src/limit_pushdown_past_window.rs:
##########
@@ -0,0 +1,145 @@
+// 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 itertools::Itertools;
+use std::cmp;
+use std::sync::Arc;
+
+#[derive(Default, Clone, Debug)]
+pub struct LimitPusher;
+
+impl LimitPusher {
+    pub fn new() -> Self {
+        Self
+    }
+}
+
+// Note: this can probably be combined with [LimitPushdown] but is independent 
now for PoC
+impl PhysicalOptimizerRule for LimitPusher {
+    fn optimize(
+        &self,
+        original: Arc<dyn ExecutionPlan>,
+        config: &ConfigOptions,
+    ) -> datafusion_common::Result<Arc<dyn ExecutionPlan>> {
+        if !config.optimizer.enable_window_limits {
+            return Ok(original);
+        }
+        // println!("-------------------------------");
+        // println!("{}", 
DisplayableExecutionPlan::new(original.as_ref()).indent(false));
+        let mut latest_limit: Option<usize> = None;
+        let mut latest_min = 0;
+        let mut latest_max = 0;
+        let result = original.transform_down(|node| {
+            // println!("Transforming {:?}", node.name());
+            let mut reset = |node| -> datafusion_common::Result<
+                Transformed<Arc<dyn ExecutionPlan>>,
+            > {
+                latest_limit = None;
+                latest_min = 0;
+                latest_max = 0;
+                Ok(Transformed::no(node))
+            };
+
+            // grab the latest limit we see
+            if let Some(limit) = 
node.as_any().downcast_ref::<GlobalLimitExec>() {
+                latest_limit = limit.fetch();
+                latest_min = 0;
+                latest_max = 0;
+                // println!("Saving limit {:?}", latest_limit);
+                return Ok(Transformed::no(node));
+            }
+
+            // grow the limit if we hit a window function
+            if let Some(window) = 
node.as_any().downcast_ref::<BoundedWindowAggExec>() {
+                let Ok(expr) = window.window_expr().iter().exactly_one() else {
+                    return reset(node);
+                };
+                let frame = expr.get_window_frame();
+                if frame.units != WindowFrameUnits::Rows {
+                    return reset(node);
+                }
+                let Some(start_bound) = bound_to_i64(&frame.start_bound) else {
+                    return reset(node);
+                };
+                let Some(end_bound) = bound_to_i64(&frame.end_bound) else {
+                    return reset(node);
+                };
+                latest_min = cmp::min(start_bound, latest_min);
+                latest_min = cmp::min(end_bound, latest_min);
+                latest_max = cmp::max(start_bound, latest_max);
+                latest_max = cmp::max(end_bound, latest_max);
+
+                return Ok(Transformed::no(node));
+            }
+
+            // we can't push the limit past nodes that change row count
+            match node.cardinality_effect() {
+                CardinalityEffect::Equal => {}
+                _ => {
+                    // println!("bailing due to cardinality change");
+                    return reset(node);
+                }
+            }
+
+            // Apply the limit if we hit a sort node
+            if let Some(sort) = node.as_any().downcast_ref::<SortExec>() {
+                if let Some(fetch) = latest_limit {
+                    let window_size = (latest_max - latest_min) as usize;
+                    let sort = sort.with_fetch(Some(fetch + window_size));

Review Comment:
   I think you're correct, because this rule comes after `EnforceSorting`, 
which sometimes flips PRECEDING/FOLLOWING 
https://github.com/apache/datafusion/pull/4691. 



-- 
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: github-unsubscr...@datafusion.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscr...@datafusion.apache.org
For additional commands, e-mail: github-h...@datafusion.apache.org

Reply via email to