akurmustafa commented on code in PR #17347: URL: https://github.com/apache/datafusion/pull/17347#discussion_r2310673423
########## 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: As far as I can see, we update `latest_max` only for `WindowFrameUnits::Rows` cases. If I am not mistaken, it is also valid to update `latest_max` for `WindowFrameUnits::Range` and `WindowFrameUnits::Groups` as longs as `end_bound` is `WindowFrameBound::Preceding(_)`. I think, we can extend checks to include this use case also. This should change the plan for following kind of queries ```sql SELECT c9, SUM(c9) OVER(ORDER BY c9 ASC RANGE BETWEEN 5 PRECEDING AND 1 PRECEDING) as sum1 FROM aggregate_test_100 LIMIT 5 ``` However, we can do this change in subsequent PRs. I think in current form, this PR is correct and we can merge as is. Thanks @avantgardnerio for this PR. -- 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]
