You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "mingmwang (via GitHub)" <gi...@apache.org> on 2023/02/22 09:43:42 UTC

[GitHub] [arrow-datafusion] mingmwang commented on a diff in pull request #5290: TopDown EnforceSorting implementation

mingmwang commented on code in PR #5290:
URL: https://github.com/apache/arrow-datafusion/pull/5290#discussion_r1114074800


##########
datafusion/core/src/physical_optimizer/sort_enforcement2.rs:
##########
@@ -0,0 +1,2872 @@
+// 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.
+
+//! EnforceSorting optimizer rule inspects the physical plan with respect
+//! to local sorting requirements and does the following:
+//! - Adds a [SortExec] when a requirement is not met,
+//! - Removes an already-existing [SortExec] if it is possible to prove
+//!   that this sort is unnecessary
+//! The rule can work on valid *and* invalid physical plans with respect to
+//! sorting requirements, but always produces a valid physical plan in this sense.
+//!
+//! A non-realistic but easy to follow example for sort removals: Assume that we
+//! somehow get the fragment
+//!
+//! ```text
+//! SortExec: expr=[nullable_col@0 ASC]
+//!   SortExec: expr=[non_nullable_col@1 ASC]
+//! ```
+//!
+//! in the physical plan. The child sort is unnecessary since its result is overwritten
+//! by the parent SortExec. Therefore, this rule removes it from the physical plan.
+use crate::config::ConfigOptions;
+use crate::error::Result;
+use crate::execution::context::TaskContext;
+use crate::physical_optimizer::utils::add_sort_above;
+use crate::physical_optimizer::PhysicalOptimizerRule;
+use crate::physical_plan::coalesce_partitions::CoalescePartitionsExec;
+use crate::physical_plan::filter::FilterExec;
+use crate::physical_plan::joins::utils::JoinSide;
+use crate::physical_plan::joins::SortMergeJoinExec;
+use crate::physical_plan::limit::{GlobalLimitExec, LocalLimitExec};
+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::sorts::sort_preserving_merge::SortPreservingMergeExec;
+use crate::physical_plan::union::UnionExec;
+use crate::physical_plan::windows::{BoundedWindowAggExec, WindowAggExec};
+use crate::physical_plan::{
+    with_new_children_if_necessary, DisplayFormatType, Distribution, ExecutionPlan,
+    Partitioning, SendableRecordBatchStream,
+};
+use arrow::datatypes::SchemaRef;
+use datafusion_common::{reverse_sort_options, DataFusionError, Statistics};
+use datafusion_expr::JoinType;
+use datafusion_physical_expr::expressions::Column;
+use datafusion_physical_expr::utils::{
+    create_sort_expr_from_requirement, map_requirement_before_projection,
+    ordering_satisfy, ordering_satisfy_requirement, requirements_compatible,
+};
+use datafusion_physical_expr::window::WindowExpr;
+use datafusion_physical_expr::{
+    new_sort_requirements, EquivalenceProperties, PhysicalExpr, PhysicalSortExpr,
+    PhysicalSortRequirements,
+};
+use itertools::izip;
+use std::any::Any;
+use std::ops::Deref;
+use std::sync::Arc;
+
+/// This rule implements a Top-Down approach to inspects SortExec's in the given physical plan and removes the
+/// ones it can prove unnecessary.
+#[derive(Default)]
+pub struct TopDownEnforceSorting {}
+
+impl TopDownEnforceSorting {
+    #[allow(missing_docs)]
+    pub fn new() -> Self {
+        Self {}
+    }
+}
+
+/// This is a "data class" we use within the [TopDownEnforceSorting] rule
+#[derive(Debug, Clone)]
+struct PlanWithSortRequirements {
+    /// Current plan
+    plan: Arc<dyn ExecutionPlan>,
+    /// Whether the plan could impact the final result ordering
+    impact_result_ordering: bool,
+    /// Parent has the SinglePartition requirement to children
+    satisfy_single_distribution: bool,
+    /// Parent required sort ordering
+    required_ordering: Option<Vec<PhysicalSortRequirements>>,
+    /// The adjusted request sort ordering to children.
+    /// By default they are the same as the plan's required input ordering, but can be adjusted based on parent required sort ordering properties.
+    adjusted_request_ordering: Vec<Option<Vec<PhysicalSortRequirements>>>,
+}
+
+impl PlanWithSortRequirements {
+    pub fn init(plan: Arc<dyn ExecutionPlan>) -> Self {
+        let impact_result_ordering = plan.output_ordering().is_some()
+            || plan.output_partitioning().partition_count() <= 1
+            || plan.as_any().downcast_ref::<GlobalLimitExec>().is_some()
+            || plan.as_any().downcast_ref::<LocalLimitExec>().is_some();

Review Comment:
   Sure, will do.



-- 
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