|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +//! Replace eligible [`SortPreservingMergeExec`] operators with the parallel |
| 19 | +//! [`ParallelSortPreservingMergeExec`]. |
| 20 | +//! |
| 21 | +//! Gated by the `datafusion.optimizer.enable_parallel_sort_merge` config flag. |
| 22 | +//! See [`ParallelSortPreservingMergeExec`] for the algorithm. |
| 23 | +
|
| 24 | +use std::sync::Arc; |
| 25 | + |
| 26 | +use crate::PhysicalOptimizerRule; |
| 27 | +use datafusion_common::Result; |
| 28 | +use datafusion_common::config::ConfigOptions; |
| 29 | +use datafusion_common::tree_node::{Transformed, TransformedResult, TreeNode}; |
| 30 | +use datafusion_physical_plan::execution_plan::Boundedness; |
| 31 | +use datafusion_physical_plan::sorts::parallel_merge::ParallelSortPreservingMergeExec; |
| 32 | +use datafusion_physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec; |
| 33 | +use datafusion_physical_plan::statistics::StatisticsArgs; |
| 34 | +use datafusion_physical_plan::{ExecutionPlan, ExecutionPlanProperties}; |
| 35 | + |
| 36 | +/// Optimizer rule that swaps [`SortPreservingMergeExec`] for the parallel |
| 37 | +/// [`ParallelSortPreservingMergeExec`] when it is both safe and beneficial. |
| 38 | +#[derive(Debug, Clone, Default)] |
| 39 | +pub struct ParallelSortMerge {} |
| 40 | + |
| 41 | +impl ParallelSortMerge { |
| 42 | + pub fn new() -> Self { |
| 43 | + Self {} |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl PhysicalOptimizerRule for ParallelSortMerge { |
| 48 | + fn optimize( |
| 49 | + &self, |
| 50 | + plan: Arc<dyn ExecutionPlan>, |
| 51 | + config: &ConfigOptions, |
| 52 | + ) -> Result<Arc<dyn ExecutionPlan>> { |
| 53 | + if !config.optimizer.enable_parallel_sort_merge { |
| 54 | + return Ok(plan); |
| 55 | + } |
| 56 | + // With a single target partition there is nothing to parallelize. |
| 57 | + if config.execution.target_partitions <= 1 { |
| 58 | + return Ok(plan); |
| 59 | + } |
| 60 | + |
| 61 | + // Only parallelize merges whose input is large enough to split into |
| 62 | + // more than one bucket; below this the materialization + sampling |
| 63 | + // overhead outweighs the benefit and a single-threaded merge is faster. |
| 64 | + let min_rows = config |
| 65 | + .execution |
| 66 | + .batch_size |
| 67 | + .get() |
| 68 | + .saturating_mul(config.execution.target_partitions); |
| 69 | + |
| 70 | + plan.transform_up(|plan: Arc<dyn ExecutionPlan>| { |
| 71 | + let Some(spm) = plan.downcast_ref::<SortPreservingMergeExec>() else { |
| 72 | + return Ok(Transformed::no(plan)); |
| 73 | + }; |
| 74 | + let input = spm.input(); |
| 75 | + |
| 76 | + // The parallel merge materializes its input and emits no rows until |
| 77 | + // it has merged everything, so it cannot satisfy a fetch/limit |
| 78 | + // (which `SortPreservingMergeExec` streams and stops early on) and |
| 79 | + // must not be used on unbounded input. It also needs more than one |
| 80 | + // input partition to be worth parallelizing. |
| 81 | + let eligible = spm.fetch().is_none() |
| 82 | + && matches!(input.boundedness(), Boundedness::Bounded) |
| 83 | + && input.output_partitioning().partition_count() > 1; |
| 84 | + |
| 85 | + if !eligible { |
| 86 | + return Ok(Transformed::no(plan)); |
| 87 | + } |
| 88 | + |
| 89 | + // Only parallelize when the input is *known* to be large enough to |
| 90 | + // benefit. The parallel merge materializes its input and pays a |
| 91 | + // sampling + task-spawn overhead, so for small (or unknown-size) |
| 92 | + // inputs the single-threaded merge is faster; when the row count is |
| 93 | + // unavailable we conservatively keep the serial merge. |
| 94 | + let Some(rows) = input |
| 95 | + .statistics_with_args(&StatisticsArgs::new()) |
| 96 | + .ok() |
| 97 | + .and_then(|stats| stats.num_rows.get_value().copied()) |
| 98 | + else { |
| 99 | + return Ok(Transformed::no(plan)); |
| 100 | + }; |
| 101 | + if rows < min_rows { |
| 102 | + return Ok(Transformed::no(plan)); |
| 103 | + } |
| 104 | + |
| 105 | + let parallel = ParallelSortPreservingMergeExec::new( |
| 106 | + spm.expr().clone(), |
| 107 | + Arc::clone(input), |
| 108 | + ); |
| 109 | + Ok(Transformed::yes(Arc::new(parallel))) |
| 110 | + }) |
| 111 | + .data() |
| 112 | + } |
| 113 | + |
| 114 | + fn name(&self) -> &str { |
| 115 | + "ParallelSortMerge" |
| 116 | + } |
| 117 | + |
| 118 | + fn schema_check(&self) -> bool { |
| 119 | + true |
| 120 | + } |
| 121 | +} |
0 commit comments