ozankabak commented on code in PR #6921:
URL: https://github.com/apache/arrow-datafusion/pull/6921#discussion_r1261699592


##########
datafusion/core/src/physical_optimizer/replace_repartition_execs.rs:
##########
@@ -0,0 +1,791 @@
+// 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.
+
+//! Repartition optimizer that replaces `SortExec`s and their suitable 
`RepartitionExec` children with `SortPreservingRepartitionExec`s.
+use crate::error::Result;
+use crate::physical_optimizer::sort_enforcement::unbounded_output;
+use crate::physical_plan::repartition::RepartitionExec;
+use crate::physical_plan::sorts::sort::SortExec;
+use crate::physical_plan::ExecutionPlan;
+
+use super::utils::is_repartition;
+
+use datafusion_common::tree_node::Transformed;
+use datafusion_physical_expr::utils::ordering_satisfy;
+
+use itertools::enumerate;
+use std::sync::Arc;
+
+/// Creates a `SortPreservingRepartitionExec` from given `RepartitionExec`
+fn sort_preserving_repartition(
+    repartition: &RepartitionExec,
+) -> Result<Arc<RepartitionExec>> {
+    Ok(Arc::new(
+        RepartitionExec::try_new(
+            repartition.input().clone(),
+            repartition.partitioning().clone(),
+        )?
+        .with_preserve_order(),
+    ))
+}
+
+fn does_plan_maintain_input_order(plan: &Arc<dyn ExecutionPlan>) -> bool {
+    plan.maintains_input_order().iter().any(|flag| *flag)
+}
+
+/// Check the children nodes of a `SortExec` until ordering is lost (e.g. until
+/// another `SortExec` or a `CoalescePartitionsExec` which doesn't maintain 
ordering)
+/// and replace `RepartitionExec`s that do not maintain ordering (e.g. those 
whose
+/// input partition counts are larger than unity) with 
`SortPreservingRepartitionExec`s.
+/// Note that doing this may render the `SortExec` in question unneccessary, 
which will
+/// be removed later on.
+///
+/// For example, we transform the plan below
+/// "FilterExec: c@2 > 3",
+/// "  RepartitionExec: partitioning=Hash(\[b@0], 16), input_partitions=16",
+/// "    RepartitionExec: partitioning=Hash(\[a@0], 16), input_partitions=1",
+/// "      MemoryExec: partitions=1, 
partition_sizes=\[(<depends_on_batch_size>)], output_ordering: 
\[PhysicalSortExpr { expr: Column { name: \"a\", index: 0 }, options: 
SortOptions { descending: false, nulls_first: false } }]",
+/// into
+/// "FilterExec: c@2 > 3",
+/// "  SortPreservingRepartitionExec: partitioning=Hash(\[b@0], 16), 
input_partitions=16",
+/// "    RepartitionExec: partitioning=Hash(\[a@0], 16), input_partitions=1",
+/// "      MemoryExec: partitions=1, 
partition_sizes=\[<depends_on_batch_size>], output_ordering: \[PhysicalSortExpr 
{ expr: Column { name: \"a\", index: 0 }, options: SortOptions { descending: 
false, nulls_first: false } }]",
+/// where the `FilterExec` in the latter has output ordering `a ASC`. This 
ordering will
+/// potentially remove a `SortExec` at the top of `FilterExec`. If this 
doesn't help remove
+/// a `SortExec`, the old version is used.
+fn replace_sort_children(
+    plan: &Arc<dyn ExecutionPlan>,
+) -> Result<Arc<dyn ExecutionPlan>> {
+    if plan.children().is_empty() {
+        return Ok(plan.clone());
+    }
+
+    let mut children = plan.children();
+    for (idx, child) in enumerate(plan.children()) {
+        if !is_repartition(&child) && !does_plan_maintain_input_order(&child) {
+            break;
+        }
+
+        if let Some(repartition) = 
child.as_any().downcast_ref::<RepartitionExec>() {
+            // Replace this `RepartitionExec` with a 
`SortPreservingRepartitionExec`
+            // if it doesn't preserve ordering and its input is unbounded. 
Doing
+            // so avoids breaking the pipeline.
+            if !repartition.maintains_input_order()[0] && 
unbounded_output(&child) {

Review Comment:
   Our benchmark results (given in the PR body) suggest that using 
`SortPreservingRepartitionExec` doesn't help when using large batch sizes. This 
is why we use it for unbounded streams for now. We plan to revisit this if/when 
we can improve `SortPreservingRepartitionExec`'s performance to exceed that of 
`RepartitionExec`'s in all cases.



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

Reply via email to