You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "waynexia (via GitHub)" <gi...@apache.org> on 2023/06/12 08:48:27 UTC

[GitHub] [arrow-datafusion] waynexia opened a new pull request, #6645: feat: encapsulate physical optimizer rules into a struct

waynexia opened a new pull request, #6645:
URL: https://github.com/apache/arrow-datafusion/pull/6645

   # Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #.
   
   # Rationale for this change
   
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   Make a new struct `PhysicalOptimizer` to hold all physical optimizer rules. Like `Optimizer` for logical rules and `Analyzer` for analyzer rules.
   
   # What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   
   New struct `PhysicalOptimizer` and several related methods on it.
   
   # Are these changes tested?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   
   yes
   
   # Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   It's a public struct
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->


-- 
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-unsubscribe@arrow.apache.org

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


[GitHub] [arrow-datafusion] jackwener commented on a diff in pull request #6645: feat: encapsulate physical optimizer rules into a struct

Posted by "jackwener (via GitHub)" <gi...@apache.org>.
jackwener commented on code in PR #6645:
URL: https://github.com/apache/arrow-datafusion/pull/6645#discussion_r1226887782


##########
datafusion/core/src/physical_optimizer/optimizer.rs:
##########
@@ -42,3 +52,78 @@ pub trait PhysicalOptimizerRule {
     /// and should disable the schema check.
     fn schema_check(&self) -> bool;
 }
+
+/// A rule-based physical optimizer.
+#[derive(Clone)]
+pub struct PhysicalOptimizer {
+    /// All rules to apply
+    pub rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>,
+}
+
+impl Default for PhysicalOptimizer {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl PhysicalOptimizer {
+    /// Create a new optimizer using the recommended list of rules
+    pub fn new() -> Self {
+        let rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>> = vec![
+            Arc::new(AggregateStatistics::new()),
+            // Statistics-based join selection will change the Auto mode to a real join implementation,
+            // like collect left, or hash join, or future sort merge join, which will influence the
+            // EnforceDistribution and EnforceSorting rules as they decide whether to add additional
+            // repartitioning and local sorting steps to meet distribution and ordering requirements.
+            // Therefore, it should run before EnforceDistribution and EnforceSorting.
+            Arc::new(JoinSelection::new()),
+            // If the query is processing infinite inputs, the PipelineFixer rule applies the
+            // necessary transformations to make the query runnable (if it is not already runnable).
+            // If the query can not be made runnable, the rule emits an error with a diagnostic message.
+            // Since the transformations it applies may alter output partitioning properties of operators
+            // (e.g. by swapping hash join sides), this rule runs before EnforceDistribution.
+            Arc::new(PipelineFixer::new()),
+            // In order to increase the parallelism, the Repartition rule will change the
+            // output partitioning of some operators in the plan tree, which will influence
+            // other rules. Therefore, it should run as soon as possible. It is optional because:
+            // - It's not used for the distributed engine, Ballista.
+            // - It's conflicted with some parts of the EnforceDistribution, since it will
+            //   introduce additional repartitioning while EnforceDistribution aims to
+            //   reduce unnecessary repartitioning.
+            Arc::new(Repartition::new()),
+            // - Currently it will depend on the partition number to decide whether to change the
+            // single node sort to parallel local sort and merge. Therefore, GlobalSortSelection
+            // should run after the Repartition.
+            // - Since it will change the output ordering of some operators, it should run
+            // before JoinSelection and EnforceSorting, which may depend on that.
+            Arc::new(GlobalSortSelection::new()),
+            // The EnforceDistribution rule is for adding essential repartition to satisfy the required
+            // distribution. Please make sure that the whole plan tree is determined before this rule.
+            Arc::new(EnforceDistribution::new()),
+            // The CombinePartialFinalAggregate rule should be applied after the EnforceDistribution rule
+            Arc::new(CombinePartialFinalAggregate::new()),
+            // The EnforceSorting rule is for adding essential local sorting to satisfy the required
+            // ordering. Please make sure that the whole plan tree is determined before this rule.
+            // Note that one should always run this rule after running the EnforceDistribution rule
+            // as the latter may break local sorting requirements.
+            Arc::new(EnforceSorting::new()),
+            // The CoalesceBatches rule will not influence the distribution and ordering of the
+            // whole plan tree. Therefore, to avoid influencing other rules, it should run last.
+            Arc::new(CoalesceBatches::new()),
+            // The PipelineChecker rule will reject non-runnable query plans that use
+            // pipeline-breaking operators on infinite input(s). The rule generates a
+            // diagnostic error message when this happens. It makes no changes to the
+            // given query plan; i.e. it only acts as a final gatekeeping rule.
+            Arc::new(PipelineChecker::new()),
+        ];
+
+        Self::with_rules(rules)
+    }
+
+    /// Create a new optimizer with the given rules
+    pub fn with_rules(rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>) -> Self {
+        Self { rules }
+    }
+

Review Comment:
   ```suggestion
   ```



-- 
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-unsubscribe@arrow.apache.org

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


[GitHub] [arrow-datafusion] jackwener commented on a diff in pull request #6645: feat: encapsulate physical optimizer rules into a struct

Posted by "jackwener (via GitHub)" <gi...@apache.org>.
jackwener commented on code in PR #6645:
URL: https://github.com/apache/arrow-datafusion/pull/6645#discussion_r1226882113


##########
datafusion/core/src/physical_optimizer/optimizer.rs:
##########
@@ -42,3 +52,106 @@ pub trait PhysicalOptimizerRule {
     /// and should disable the schema check.
     fn schema_check(&self) -> bool;
 }
+
+/// A rule-based physical optimizer.
+#[derive(Clone)]
+pub struct PhysicalOptimizer {
+    /// All rules to apply
+    pub rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>,
+}
+
+impl Default for PhysicalOptimizer {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl PhysicalOptimizer {
+    /// Create a new optimizer using the recommended list of rules
+    pub fn new() -> Self {
+        let rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>> = vec![
+            Arc::new(AggregateStatistics::new()),
+            // Statistics-based join selection will change the Auto mode to a real join implementation,
+            // like collect left, or hash join, or future sort merge join, which will influence the
+            // EnforceDistribution and EnforceSorting rules as they decide whether to add additional
+            // repartitioning and local sorting steps to meet distribution and ordering requirements.
+            // Therefore, it should run before EnforceDistribution and EnforceSorting.
+            Arc::new(JoinSelection::new()),
+            // If the query is processing infinite inputs, the PipelineFixer rule applies the
+            // necessary transformations to make the query runnable (if it is not already runnable).
+            // If the query can not be made runnable, the rule emits an error with a diagnostic message.
+            // Since the transformations it applies may alter output partitioning properties of operators
+            // (e.g. by swapping hash join sides), this rule runs before EnforceDistribution.
+            Arc::new(PipelineFixer::new()),
+            // In order to increase the parallelism, the Repartition rule will change the
+            // output partitioning of some operators in the plan tree, which will influence
+            // other rules. Therefore, it should run as soon as possible. It is optional because:
+            // - It's not used for the distributed engine, Ballista.
+            // - It's conflicted with some parts of the EnforceDistribution, since it will
+            //   introduce additional repartitioning while EnforceDistribution aims to
+            //   reduce unnecessary repartitioning.
+            Arc::new(Repartition::new()),
+            // - Currently it will depend on the partition number to decide whether to change the
+            // single node sort to parallel local sort and merge. Therefore, GlobalSortSelection
+            // should run after the Repartition.
+            // - Since it will change the output ordering of some operators, it should run
+            // before JoinSelection and EnforceSorting, which may depend on that.
+            Arc::new(GlobalSortSelection::new()),
+            // The EnforceDistribution rule is for adding essential repartition to satisfy the required
+            // distribution. Please make sure that the whole plan tree is determined before this rule.
+            Arc::new(EnforceDistribution::new()),
+            // The CombinePartialFinalAggregate rule should be applied after the EnforceDistribution rule
+            Arc::new(CombinePartialFinalAggregate::new()),
+            // The EnforceSorting rule is for adding essential local sorting to satisfy the required
+            // ordering. Please make sure that the whole plan tree is determined before this rule.
+            // Note that one should always run this rule after running the EnforceDistribution rule
+            // as the latter may break local sorting requirements.
+            Arc::new(EnforceSorting::new()),
+            // The CoalesceBatches rule will not influence the distribution and ordering of the
+            // whole plan tree. Therefore, to avoid influencing other rules, it should run last.
+            Arc::new(CoalesceBatches::new()),
+            // The PipelineChecker rule will reject non-runnable query plans that use
+            // pipeline-breaking operators on infinite input(s). The rule generates a
+            // diagnostic error message when this happens. It makes no changes to the
+            // given query plan; i.e. it only acts as a final gatekeeping rule.
+            Arc::new(PipelineChecker::new()),
+        ];
+
+        Self::with_rules(rules)
+    }
+
+    /// Create a new optimizer with the given rules
+    pub fn with_rules(rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>) -> Self {
+        Self { rules }
+    }
+
+    /// Remove the first rule that [PhysicalOptimizerRule::name] equals to the given name.
+    /// Return whether a rule is removed.
+    pub fn remove_rule(&mut self, name: &str) -> bool {
+        let mut index_to_move = None;
+        for (index, rule) in self.rules.iter().enumerate() {
+            if rule.name() == name {
+                index_to_move = Some(index);
+                break;
+            }
+        }
+
+        if let Some(index) = index_to_move {
+            self.rules.remove(index);
+        }
+
+        index_to_move.is_some()
+    }

Review Comment:
   ```suggestion
   ```
   I think they are redundant because in general we don't need  remove a rule.



##########
datafusion/core/src/physical_optimizer/optimizer.rs:
##########
@@ -42,3 +52,106 @@ pub trait PhysicalOptimizerRule {
     /// and should disable the schema check.
     fn schema_check(&self) -> bool;
 }
+
+/// A rule-based physical optimizer.
+#[derive(Clone)]
+pub struct PhysicalOptimizer {
+    /// All rules to apply
+    pub rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>,
+}
+
+impl Default for PhysicalOptimizer {
+    fn default() -> Self {
+        Self::new()
+    }
+}
+
+impl PhysicalOptimizer {
+    /// Create a new optimizer using the recommended list of rules
+    pub fn new() -> Self {
+        let rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>> = vec![
+            Arc::new(AggregateStatistics::new()),
+            // Statistics-based join selection will change the Auto mode to a real join implementation,
+            // like collect left, or hash join, or future sort merge join, which will influence the
+            // EnforceDistribution and EnforceSorting rules as they decide whether to add additional
+            // repartitioning and local sorting steps to meet distribution and ordering requirements.
+            // Therefore, it should run before EnforceDistribution and EnforceSorting.
+            Arc::new(JoinSelection::new()),
+            // If the query is processing infinite inputs, the PipelineFixer rule applies the
+            // necessary transformations to make the query runnable (if it is not already runnable).
+            // If the query can not be made runnable, the rule emits an error with a diagnostic message.
+            // Since the transformations it applies may alter output partitioning properties of operators
+            // (e.g. by swapping hash join sides), this rule runs before EnforceDistribution.
+            Arc::new(PipelineFixer::new()),
+            // In order to increase the parallelism, the Repartition rule will change the
+            // output partitioning of some operators in the plan tree, which will influence
+            // other rules. Therefore, it should run as soon as possible. It is optional because:
+            // - It's not used for the distributed engine, Ballista.
+            // - It's conflicted with some parts of the EnforceDistribution, since it will
+            //   introduce additional repartitioning while EnforceDistribution aims to
+            //   reduce unnecessary repartitioning.
+            Arc::new(Repartition::new()),
+            // - Currently it will depend on the partition number to decide whether to change the
+            // single node sort to parallel local sort and merge. Therefore, GlobalSortSelection
+            // should run after the Repartition.
+            // - Since it will change the output ordering of some operators, it should run
+            // before JoinSelection and EnforceSorting, which may depend on that.
+            Arc::new(GlobalSortSelection::new()),
+            // The EnforceDistribution rule is for adding essential repartition to satisfy the required
+            // distribution. Please make sure that the whole plan tree is determined before this rule.
+            Arc::new(EnforceDistribution::new()),
+            // The CombinePartialFinalAggregate rule should be applied after the EnforceDistribution rule
+            Arc::new(CombinePartialFinalAggregate::new()),
+            // The EnforceSorting rule is for adding essential local sorting to satisfy the required
+            // ordering. Please make sure that the whole plan tree is determined before this rule.
+            // Note that one should always run this rule after running the EnforceDistribution rule
+            // as the latter may break local sorting requirements.
+            Arc::new(EnforceSorting::new()),
+            // The CoalesceBatches rule will not influence the distribution and ordering of the
+            // whole plan tree. Therefore, to avoid influencing other rules, it should run last.
+            Arc::new(CoalesceBatches::new()),
+            // The PipelineChecker rule will reject non-runnable query plans that use
+            // pipeline-breaking operators on infinite input(s). The rule generates a
+            // diagnostic error message when this happens. It makes no changes to the
+            // given query plan; i.e. it only acts as a final gatekeeping rule.
+            Arc::new(PipelineChecker::new()),
+        ];
+
+        Self::with_rules(rules)
+    }
+
+    /// Create a new optimizer with the given rules
+    pub fn with_rules(rules: Vec<Arc<dyn PhysicalOptimizerRule + Send + Sync>>) -> Self {
+        Self { rules }
+    }
+
+    /// Remove the first rule that [PhysicalOptimizerRule::name] equals to the given name.
+    /// Return whether a rule is removed.
+    pub fn remove_rule(&mut self, name: &str) -> bool {
+        let mut index_to_move = None;
+        for (index, rule) in self.rules.iter().enumerate() {
+            if rule.name() == name {
+                index_to_move = Some(index);
+                break;
+            }
+        }
+
+        if let Some(index) = index_to_move {
+            self.rules.remove(index);
+        }
+
+        index_to_move.is_some()
+    }
+}
+
+#[cfg(test)]
+mod test {
+    use super::*;
+
+    #[test]
+    fn remove_enforce_sorting_rule() {
+        let mut optimizer = PhysicalOptimizer::new();
+        assert!(optimizer.remove_rule(EnforceSorting {}.name()));
+        assert!(!optimizer.remove_rule(EnforceSorting {}.name()));
+    }
+}

Review Comment:
   ```suggestion
   ```



-- 
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-unsubscribe@arrow.apache.org

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


[GitHub] [arrow-datafusion] jackwener merged pull request #6645: feat: encapsulate physical optimizer rules into a struct

Posted by "jackwener (via GitHub)" <gi...@apache.org>.
jackwener merged PR #6645:
URL: https://github.com/apache/arrow-datafusion/pull/6645


-- 
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-unsubscribe@arrow.apache.org

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


[GitHub] [arrow-datafusion] waynexia commented on pull request #6645: feat: encapsulate physical optimizer rules into a struct

Posted by "waynexia (via GitHub)" <gi...@apache.org>.
waynexia commented on PR #6645:
URL: https://github.com/apache/arrow-datafusion/pull/6645#issuecomment-1595945385

   Thanks for reviewing it :heart:
   
   >I think they are redundant because in general we don't need remove a rule.
   
   🥹 It would be useful when I want to adjust the order of rules (by removing it and inserting a new one). But it's ok since the inner vector is public anyway


-- 
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-unsubscribe@arrow.apache.org

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