mingmwang commented on code in PR #4122: URL: https://github.com/apache/arrow-datafusion/pull/4122#discussion_r1018012590
########## datafusion/core/src/physical_optimizer/enforcement.rs: ########## @@ -0,0 +1,2001 @@ +// 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. + +//! Enforcement optimizer rules are used to make sure the plan's Distribution and Ordering +//! requirements are met by inserting necessary [[RepartitionExec]] and [[SortExec]]. +//! +use crate::error::Result; +use crate::physical_optimizer::PhysicalOptimizerRule; +use crate::physical_plan::aggregates::{AggregateExec, AggregateMode, PhysicalGroupBy}; +use crate::physical_plan::coalesce_partitions::CoalescePartitionsExec; +use crate::physical_plan::joins::{ + CrossJoinExec, HashJoinExec, PartitionMode, SortMergeJoinExec, +}; +use crate::physical_plan::projection::ProjectionExec; +use crate::physical_plan::repartition::RepartitionExec; +use crate::physical_plan::rewrite::TreeNodeRewritable; +use crate::physical_plan::sorts::sort::SortExec; +use crate::physical_plan::windows::WindowAggExec; +use crate::physical_plan::Partitioning; +use crate::physical_plan::{with_new_children_if_necessary, Distribution, ExecutionPlan}; +use crate::prelude::SessionConfig; +use datafusion_expr::logical_plan::JoinType; +use datafusion_physical_expr::equivalence::EquivalenceProperties; +use datafusion_physical_expr::expressions::Column; +use datafusion_physical_expr::expressions::NoOp; +use datafusion_physical_expr::{ + expr_list_eq_strict_order, normalize_expr_with_equivalence_properties, + normalize_sort_expr_with_equivalence_properties, PhysicalExpr, PhysicalSortExpr, +}; +use std::collections::HashMap; +use std::sync::Arc; + +/// BasicEnforcement rule, it ensures the Distribution and Ordering requirements are met +/// in the strictest way. It might add additional [[RepartitionExec]] to the plan tree +/// and give a non-optimal plan, but it can avoid the possible data skew in joins +/// +/// For example for a HashJoin with keys(a, b, c), the required Distribution(a, b, c) can be satisfied by +/// several alternative partitioning ways: [(a, b, c), (a, b), (a, c), (b, c), (a), (b), (c), ( )]. +/// +/// This rule only chooses the exactly match and satisfies the Distribution(a, b, c) by a HashPartition(a, b, c). +#[derive(Default)] +pub struct BasicEnforcement {} + +impl BasicEnforcement { + #[allow(missing_docs)] + pub fn new() -> Self { + Self {} + } +} + +impl PhysicalOptimizerRule for BasicEnforcement { + fn optimize( + &self, + plan: Arc<dyn ExecutionPlan>, + config: &SessionConfig, + ) -> Result<Arc<dyn ExecutionPlan>> { + let target_partitions = config.target_partitions; + let top_down_join_key_reordering = config.top_down_join_key_reordering; + let new_plan = if top_down_join_key_reordering { + // Run a top-down process to adjust input key ordering recursively + adjust_input_keys_down_recursively(plan, vec![])? + } else { + plan + }; + // Distribution and Ordering enforcement need to be applied bottom-up. + new_plan.transform_up(&{ + |plan| { + let adjusted = if !top_down_join_key_reordering { + reorder_join_keys_to_inputs(plan) + } else { + plan + }; + Some(ensure_distribution_and_ordering( + adjusted, + target_partitions, + )) + } + }) + } + + fn name(&self) -> &str { + "BasicEnforcement" + } +} + +/// When the physical planner creates the Joins, the ordering of join keys is from the original query. Review Comment: Yes, this is to cover the cases that complex plan graphs which include multiple joins or join on aggregations but key orderings are different. For example: ```` TopJoin on (a, b, c) bottom left join on(b, a, c) bottom right join on(c, b, a) ```` Another case: ```` TopJoin on (a, b, c) Agg1 group by (b, a, c) Agg2 group by (c, b, a) ```` The PR comes up with two join key reordering implementations: 1) Top-down approach, see the method `fn adjust_input_keys_down_recursively()` The top down approach will adjust the children's key ordering based on parent requirements: ```` TopJoin on (a, b, c) bottom left join on(b, a, c) bottom right join on(c, b, a) ```` will be adjusted to ```` TopJoin on (a, b, c) bottom left join on(a, b, c) bottom right join on(a, b, c) ```` ```` TopJoin on (a, b, c) Agg1 group by (b, a, c) Agg2 group by (c, b, a) ```` will be adjusted to: ```` TopJoin on (a, b, c) Projection(b, a, c) Agg1 group by (a, b, c) Projection(c, b, a) Agg2 group by (a, b, c) ```` 2) Bottom-up approach, see the method `fn reorder_join_keys_to_inputs()` The Bottom-up approach will just adjust the parent's key ordering based on children's, either align with left or right, sometimes can not align with both. The Bottom up approach is much simpler than the top-down approach, but might not reach a best result. ```` TopJoin on (a, b, c) bottom left join on(b, a, c) bottom right join on(c, b, a) ```` will be adjusted to ```` TopJoin on (b, a, c) bottom left join on(b, a, c) bottom right join on(c, b, a) ```` And by default, the PR go with the top-down approach, and there is a session level configuration `config.top_down_join_key_reordering `to disable it. The bottom-up approach will be useful in future if we plan to support storage partition-wised joins. In that case, the data sources/tables might be pre-partitioned and we can't adjust the order, so we would prefer to adjust parent's key ordering based on children's. -- 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]
