Skip to content

Apache DataFusion SQL Query Engine

Remove constant expressions from SortExprs in the SortExec (#9618)

Mustafa Akur451d13a88af7
diff --git a/datafusion/core/src/physical_optimizer/enforce_distribution.rs b/datafusion/core/src/physical_optimizer/enforce_distribution.rs
index 60ee1e20a9..54fe6e8406 100644
--- a/datafusion/core/src/physical_optimizer/enforce_distribution.rs
+++ b/datafusion/core/src/physical_optimizer/enforce_distribution.rs
@@ -28,7 +28,8 @@ use super::output_requirements::OutputRequirementExec;
use crate::config::ConfigOptions;
use crate::error::Result;
use crate::physical_optimizer::utils::{
- is_coalesce_partitions, is_repartition, is_sort_preserving_merge,
+ add_sort_above_with_check, is_coalesce_partitions, is_repartition,
+ is_sort_preserving_merge,
};
use crate::physical_optimizer::PhysicalOptimizerRule;
use crate::physical_plan::aggregates::{AggregateExec, AggregateMode, PhysicalGroupBy};
@@ -50,10 +51,8 @@ use datafusion_expr::logical_plan::JoinType;
use datafusion_physical_expr::expressions::{Column, NoOp};
use datafusion_physical_expr::utils::map_columns_before_projection;
use datafusion_physical_expr::{
- physical_exprs_equal, EquivalenceProperties, LexRequirementRef, PhysicalExpr,
- PhysicalExprRef, PhysicalSortRequirement,
+ physical_exprs_equal, EquivalenceProperties, PhysicalExpr, PhysicalExprRef,
};
-use datafusion_physical_plan::sorts::sort::SortExec;
use datafusion_physical_plan::windows::{get_best_fitting_window, BoundedWindowAggExec};
use datafusion_physical_plan::ExecutionPlanProperties;
@@ -1030,30 +1029,6 @@ fn replace_order_preserving_variants(
context.update_plan_from_children()
}
-/// This utility function adds a [`SortExec`] above an operator according to the
-/// given ordering requirements while preserving the original partitioning.
-fn add_sort_preserving_partitions(
- node: DistributionContext,
- sort_requirement: LexRequirementRef,
- fetch: Option<usize>,
-) -> DistributionContext {
- // If the ordering requirement is already satisfied, do not add a sort.
- if !node
- .plan
- .equivalence_properties()
- .ordering_satisfy_requirement(sort_requirement)
- {
- let sort_expr = PhysicalSortRequirement::to_sort_exprs(sort_requirement.to_vec());
- let mut new_sort = SortExec::new(sort_expr, node.plan.clone()).with_fetch(fetch);
- if node.plan.output_partitioning().partition_count() > 1 {
- new_sort = new_sort.with_preserve_partitioning(true);
- }
- DistributionContext::new(Arc::new(new_sort), false, vec![node])
- } else {
- node
- }
-}
-
/// This function checks whether we need to add additional data exchange
/// operators to satisfy distribution requirements. Since this function
/// takes care of such requirements, we should avoid manually adding data
@@ -1185,9 +1160,9 @@ fn ensure_distribution(
// make sure ordering requirements are still satisfied after.
if ordering_satisfied {
// Make sure to satisfy ordering requirement:
- child = add_sort_preserving_partitions(
+ child = add_sort_above_with_check(
child,
- required_input_ordering,
+ required_input_ordering.to_vec(),
None,
);
}
diff --git a/datafusion/core/src/physical_optimizer/enforce_sorting.rs b/datafusion/core/src/physical_optimizer/enforce_sorting.rs
index e7ad64aa87..5bf21c3dfa 100644
--- a/datafusion/core/src/physical_optimizer/enforce_sorting.rs
+++ b/datafusion/core/src/physical_optimizer/enforce_sorting.rs
@@ -36,7 +36,7 @@
use std::sync::Arc;
-use super::utils::add_sort_above;
+use super::utils::{add_sort_above, add_sort_above_with_check};
use crate::config::ConfigOptions;
use crate::error::Result;
use crate::physical_optimizer::replace_with_order_preserving_variants::{
@@ -285,13 +285,7 @@ fn parallelize_sorts(
// deals with the children and their children and so on.
requirements = requirements.children.swap_remove(0);
- if !requirements
- .plan
- .equivalence_properties()
- .ordering_satisfy_requirement(&sort_reqs)
- {
- requirements = add_sort_above(requirements, sort_reqs, fetch);
- }
+ requirements = add_sort_above_with_check(requirements, sort_reqs, fetch);
let spm = SortPreservingMergeExec::new(sort_exprs, requirements.plan.clone());
Ok(Transformed::yes(
diff --git a/datafusion/core/src/physical_optimizer/utils.rs b/datafusion/core/src/physical_optimizer/utils.rs
index 8cc543802e..2c0d042281 100644
--- a/datafusion/core/src/physical_optimizer/utils.rs
+++ b/datafusion/core/src/physical_optimizer/utils.rs
@@ -38,7 +38,13 @@ pub fn add_sort_above<T: Clone + Default>(
sort_requirements: LexRequirement,
fetch: Option<usize>,
) -> PlanContext<T> {
- let sort_expr = PhysicalSortRequirement::to_sort_exprs(sort_requirements);
+ let mut sort_expr = PhysicalSortRequirement::to_sort_exprs(sort_requirements);
+ sort_expr.retain(|sort_expr| {
+ !node
+ .plan
+ .equivalence_properties()
+ .is_expr_constant(&sort_expr.expr)
+ });
let mut new_sort = SortExec::new(sort_expr, node.plan.clone()).with_fetch(fetch);
if node.plan.output_partitioning().partition_count() > 1 {
new_sort = new_sort.with_preserve_partitioning(true);
@@ -46,6 +52,25 @@ pub fn add_sort_above<T: Clone + Default>(
PlanContext::new(Arc::new(new_sort), T::default(), vec![node])
}
+/// This utility function adds a `SortExec` above an operator according to the
+/// given ordering requirements while preserving the original partitioning. If
+/// requirement is already satisfied no `SortExec` is added.
+pub fn add_sort_above_with_check<T: Clone + Default>(
+ node: PlanContext<T>,
+ sort_requirements: LexRequirement,
+ fetch: Option<usize>,
+) -> PlanContext<T> {
+ if !node
+ .plan
+ .equivalence_properties()
+ .ordering_satisfy_requirement(&sort_requirements)
+ {
+ add_sort_above(node, sort_requirements, fetch)
+ } else {
+ node
+ }
+}
+
/// Checks whether the given operator is a limit;
/// i.e. either a [`LocalLimitExec`] or a [`GlobalLimitExec`].
pub fn is_limit(plan: &Arc<dyn ExecutionPlan>) -> bool {
diff --git a/datafusion/physical-expr/src/equivalence/properties.rs b/datafusion/physical-expr/src/equivalence/properties.rs
index 890d0b4968..a08e85b241 100644
--- a/datafusion/physical-expr/src/equivalence/properties.rs
+++ b/datafusion/physical-expr/src/equivalence/properties.rs
@@ -820,7 +820,7 @@ impl EquivalenceProperties {
///
/// Returns `true` if the expression is constant according to equivalence
/// group, `false` otherwise.
- fn is_expr_constant(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {
+ pub fn is_expr_constant(&self, expr: &Arc<dyn PhysicalExpr>) -> bool {
// As an example, assume that we know columns `a` and `b` are constant.
// Then, `a`, `b` and `a + b` will all return `true` whereas `c` will
// return `false`.
diff --git a/datafusion/sqllogictest/test_files/window.slt b/datafusion/sqllogictest/test_files/window.slt
index 29a986539c..efb180b10c 100644
--- a/datafusion/sqllogictest/test_files/window.slt
+++ b/datafusion/sqllogictest/test_files/window.slt
@@ -3407,6 +3407,44 @@ WITH ORDER (a ASC, b ASC)
WITH ORDER (c ASC)
LOCATION '../core/tests/data/window_2.csv';
+# Since column b is constant after filter b=0,
+# There should be no SortExec(b ASC) in the plan
+# window requirement b ASC is already satisfied by existing ordering.
+query TT
+EXPLAIN SELECT *, SUM(a) OVER(ORDER BY b ASC)
+FROM multiple_ordered_table
+where b=0
+----
+logical_plan
+WindowAggr: windowExpr=[[SUM(CAST(multiple_ordered_table.a AS Int64)) ORDER BY [multiple_ordered_table.b ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
+--Filter: multiple_ordered_table.b = Int32(0)
+----TableScan: multiple_ordered_table projection=[a0, a, b, c, d], partial_filters=[multiple_ordered_table.b = Int32(0)]
+physical_plan
+BoundedWindowAggExec: wdw=[SUM(multiple_ordered_table.a) ORDER BY [multiple_ordered_table.b ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Ok(Field { name: "SUM(multiple_ordered_table.a) ORDER BY [multiple_ordered_table.b ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: CurrentRow, is_causal: false }], mode=[Sorted]
+--CoalesceBatchesExec: target_batch_size=4096
+----FilterExec: b@2 = 0
+------CsvExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a0, a, b, c, d], output_orderings=[[a@1 ASC NULLS LAST, b@2 ASC NULLS LAST], [c@3 ASC NULLS LAST]], has_header=true
+
+# Since column b is constant after filter b=0,
+# window requirement b ASC, d ASC can be satisfied
+# by the SortExec(d ASC). We do not need to sort by [b ASC, d ASC]
+query TT
+EXPLAIN SELECT *, SUM(a) OVER(ORDER BY b ASC, d ASC)
+FROM multiple_ordered_table
+where b=0
+----
+logical_plan
+WindowAggr: windowExpr=[[SUM(CAST(multiple_ordered_table.a AS Int64)) ORDER BY [multiple_ordered_table.b ASC NULLS LAST, multiple_ordered_table.d ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW]]
+--Filter: multiple_ordered_table.b = Int32(0)
+----TableScan: multiple_ordered_table projection=[a0, a, b, c, d], partial_filters=[multiple_ordered_table.b = Int32(0)]
+physical_plan
+BoundedWindowAggExec: wdw=[SUM(multiple_ordered_table.a) ORDER BY [multiple_ordered_table.b ASC NULLS LAST, multiple_ordered_table.d ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW: Ok(Field { name: "SUM(multiple_ordered_table.a) ORDER BY [multiple_ordered_table.b ASC NULLS LAST, multiple_ordered_table.d ASC NULLS LAST] RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW", data_type: Int64, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }), frame: WindowFrame { units: Range, start_bound: Preceding(Int32(NULL)), end_bound: CurrentRow, is_causal: false }], mode=[Sorted]
+--SortExec: expr=[d@4 ASC NULLS LAST]
+----CoalesceBatchesExec: target_batch_size=4096
+------FilterExec: b@2 = 0
+--------CsvExec: file_groups={1 group: [[WORKSPACE_ROOT/datafusion/core/tests/data/window_2.csv]]}, projection=[a0, a, b, c, d], output_orderings=[[a@1 ASC NULLS LAST, b@2 ASC NULLS LAST], [c@3 ASC NULLS LAST]], has_header=true
+
+
# Create an unbounded source where there is multiple orderings.
statement ok
CREATE UNBOUNDED EXTERNAL TABLE multiple_ordered_table_inf (