mingmwang commented on code in PR #3855: URL: https://github.com/apache/arrow-datafusion/pull/3855#discussion_r998930603
########## datafusion/core/src/physical_optimizer/enforcement.rs: ########## @@ -0,0 +1,858 @@ +// 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::utils::transform_up; +use crate::physical_optimizer::PhysicalOptimizerRule; +use crate::physical_plan::coalesce_partitions::CoalescePartitionsExec; +use crate::physical_plan::repartition::RepartitionExec; +use crate::physical_plan::sorts::sort::SortExec; +use crate::physical_plan::{with_new_children_if_necessary, Distribution, ExecutionPlan}; +use crate::prelude::SessionConfig; +use datafusion_physical_expr::expressions::Column; +use datafusion_physical_expr::{ + normalize_sort_expr_with_equivalence_properties, PhysicalSortExpr, +}; +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>> { + // Distribution and Ordering enforcement need to be applied bottom-up. + let target_partitions = config.target_partitions; + transform_up(plan, &{ + |plan| Some(ensure_distribution_and_ordering(plan, target_partitions)) + }) + } + + fn name(&self) -> &str { + "BasicEnforcement" + } +} + +fn ensure_distribution_and_ordering( + plan: Arc<dyn crate::physical_plan::ExecutionPlan>, + target_partitions: usize, +) -> Arc<dyn crate::physical_plan::ExecutionPlan> { + if plan.children().is_empty() { + return plan; + } + let required_input_distributions = plan.required_input_distribution(); + let required_input_orderings = plan.required_input_ordering(); + let children: Vec<Arc<dyn ExecutionPlan>> = plan.children(); + assert_eq!(children.len(), required_input_distributions.len()); + assert_eq!(children.len(), required_input_orderings.len()); + + // Add RepartitionExec to guarantee output partitioning + let children = children + .into_iter() + .zip(required_input_distributions.into_iter()) + .map(|(child, required)| { + if child + .output_partitioning() + .satisfy(required.clone(), || child.equivalence_properties()) + { + child + } else { + let new_child: Arc<dyn ExecutionPlan> = match required { + Distribution::SinglePartition + if child.output_partitioning().partition_count() > 1 => + { + Arc::new(CoalescePartitionsExec::new(child.clone())) + } + _ => { + let partition = required.create_partitioning(target_partitions); + Arc::new(RepartitionExec::try_new(child, partition).unwrap()) + } + }; + new_child + } + }); + + // Add SortExec to guarantee output ordering + let new_children: Vec<Arc<dyn ExecutionPlan>> = children + .zip(required_input_orderings.into_iter()) + .map(|(child, required)| { + if ordering_satisfy(child.output_ordering(), required, || { + child.equivalence_properties() + }) { + child + } else { + let sort_expr = required.unwrap().to_vec(); + if child.output_partitioning().partition_count() > 1 { + Arc::new(SortExec::new_with_partitioning( + sort_expr, child, true, None, + )) + } else { + Arc::new(SortExec::try_new(sort_expr, child, None).unwrap()) + } + } + }) + .collect::<Vec<_>>(); + + with_new_children_if_necessary(plan, new_children).unwrap() +} + +/// DynamicEnforcement rule +/// +/// +#[derive(Default)] +pub struct DynamicEnforcement {} + +// TODO Review Comment: > This is looking pretty neat @mingmwang but it is basically impossible for me to carefully review such a large PR. I wonder if you can break it down into pieces so we can get it in? > > Possible split: > > 1. Add `PhysicalExpr::children()` and `PhysicalExpr::new_with_children` > 2. the code for iterating / manipulating physical exprs > 3. The code for calculating equivalence properties (and tests) > 4. The code in datafusion/core/src/physical_optimizer/enforcement.rs Sure, I will split this PR to the 3 PRs: 1. PhysicalExpr related change: implement PartialEq<dyn Any> for PhysicalExpr, PhysicalExpr::children() and PhysicalExpr::new_with_children, the utils code for iterating / manipulating physical exprs. 2. Execution plan related changes: output_partitioning(), output_ordering(), required_input_distribution(), the code for calculating equivalence properties (and tests) 3. The code in datafusion/core/src/physical_optimizer/enforcement.rs and the tests. -- 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]
