Skip to content

Commit d3a3430

Browse files
committed
perf: share one augmented mapping when projecting an equivalence group
`EquivalenceGroup::project` called `project_expressions` once per class, and each call built its own augmented projection mapping the first time a member was not a direct source. Building that mapping looks up every source of the projection, so projecting a group with many classes cost the number of classes times the projection width. Groups with many constant classes, such as inputs that pad columns with typed nulls, hit this on every projection the planner builds. The mapping is now built at most once per `project` call and shared by all classes. Literals are returned before the mapping is built, as `project_expr_indirect` already returned them unchanged, so a class whose only indirect members are literals no longer builds it at all. `project_expr` uses the same helper.
1 parent bd7e3b6 commit d3a3430

1 file changed

Lines changed: 104 additions & 24 deletions

File tree

  • datafusion/physical-expr/src/equivalence

‎datafusion/physical-expr/src/equivalence/class.rs‎

Lines changed: 104 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -665,14 +665,7 @@ impl EquivalenceGroup {
665665
mapping: &ProjectionMapping,
666666
expr: &Arc<dyn PhysicalExpr>,
667667
) -> Option<Arc<dyn PhysicalExpr>> {
668-
if let Some(targets) = mapping.get(expr) {
669-
// If we match the source, we can project directly:
670-
let (target, _) = targets.first();
671-
Some(Arc::clone(target))
672-
} else {
673-
let aug_mapping = self.augment_projection_mapping(mapping);
674-
Self::project_expr_indirect(&aug_mapping, expr)
675-
}
668+
self.project_expr_sharing(mapping, &mut None, expr)
676669
}
677670

678671
/// Projects `expressions` according to the given projection mapping.
@@ -685,25 +678,50 @@ impl EquivalenceGroup {
685678
expressions: impl IntoIterator<Item = &'a Arc<dyn PhysicalExpr>> + 'a,
686679
) -> impl Iterator<Item = Option<Arc<dyn PhysicalExpr>>> + 'a {
687680
let mut aug_mapping = None;
688-
expressions.into_iter().map(move |expr| {
689-
if let Some(targets) = mapping.get(expr) {
690-
// If we match the source, we can project directly:
691-
let (target, _) = targets.first();
692-
Some(Arc::clone(target))
693-
} else {
694-
let aug_mapping = aug_mapping
695-
.get_or_insert_with(|| self.augment_projection_mapping(mapping));
696-
Self::project_expr_indirect(aug_mapping, expr)
697-
}
698-
})
681+
expressions
682+
.into_iter()
683+
.map(move |expr| self.project_expr_sharing(mapping, &mut aug_mapping, expr))
684+
}
685+
686+
/// Projects `expr` like [`Self::project_expr`], building the augmented
687+
/// mapping into `aug_mapping` only when an indirect projection needs it.
688+
///
689+
/// Building that mapping looks up every source expression of `mapping`, so
690+
/// callers that project many expressions share one across all of them.
691+
fn project_expr_sharing<'a>(
692+
&'a self,
693+
mapping: &'a ProjectionMapping,
694+
aug_mapping: &mut Option<AugmentedMapping<'a>>,
695+
expr: &Arc<dyn PhysicalExpr>,
696+
) -> Option<Arc<dyn PhysicalExpr>> {
697+
if let Some(targets) = mapping.get(expr) {
698+
// If we match the source, we can project directly:
699+
let (target, _) = targets.first();
700+
return Some(Arc::clone(target));
701+
}
702+
// Literals don't need to be projected
703+
if expr.downcast_ref::<Literal>().is_some() {
704+
return Some(Arc::clone(expr));
705+
}
706+
let aug_mapping =
707+
aug_mapping.get_or_insert_with(|| self.augment_projection_mapping(mapping));
708+
Self::project_expr_indirect(aug_mapping, expr)
699709
}
700710

701711
/// Projects this equivalence group according to the given projection mapping.
702712
pub fn project(&self, mapping: &ProjectionMapping) -> Self {
703-
let projected_classes = self.iter().map(|cls| {
704-
let new_exprs = self.project_expressions(mapping, cls.iter());
705-
EquivalenceClass::new(new_exprs.flatten())
706-
});
713+
// One augmented mapping serves every class. Building it per class made
714+
// projecting a group with many classes quadratic.
715+
let mut aug_mapping = None;
716+
let projected_classes = self
717+
.iter()
718+
.map(|cls| {
719+
let new_exprs = cls.iter().filter_map(|expr| {
720+
self.project_expr_sharing(mapping, &mut aug_mapping, expr)
721+
});
722+
EquivalenceClass::new(new_exprs)
723+
})
724+
.collect::<Vec<_>>();
707725

708726
// The key is the source expression, and the value is the equivalence
709727
// class that contains the corresponding target expression.
@@ -731,6 +749,7 @@ impl EquivalenceGroup {
731749

732750
// Union projected classes with new classes to make up the result:
733751
let classes = projected_classes
752+
.into_iter()
734753
.chain(new_classes.into_values())
735754
.filter(|cls| !cls.is_trivial());
736755
let mut result = Self::new(classes);
@@ -935,7 +954,7 @@ mod tests {
935954
use super::*;
936955
use crate::equivalence::tests::create_test_params;
937956
use crate::expressions::{BinaryExpr, Column, binary, col, lit};
938-
use arrow::datatypes::{DataType, Field, Schema};
957+
use arrow::datatypes::{DataType, Field, Schema, SchemaRef};
939958

940959
use datafusion_expr::Operator;
941960

@@ -1257,6 +1276,67 @@ mod tests {
12571276
Ok(())
12581277
}
12591278

1279+
#[test]
1280+
fn test_project_classes_needing_indirect_projection() -> Result<()> {
1281+
// - columns: [a, b].
1282+
// - classes: `a + b == a + 1` and `b + 1 == a * b`.
1283+
// - projection: [a as x, b as y].
1284+
// No class member is a source of the projection, so every member is
1285+
// projected through its children: the classes become `x + y == x + 1`
1286+
// and `y + 1 == x * y`.
1287+
let schema = Arc::new(Schema::new(vec![
1288+
Field::new("a", DataType::Int32, false),
1289+
Field::new("b", DataType::Int32, false),
1290+
]));
1291+
let projected_schema = Arc::new(Schema::new(vec![
1292+
Field::new("x", DataType::Int32, false),
1293+
Field::new("y", DataType::Int32, false),
1294+
]));
1295+
let exprs = |left: &str, right: &str, schema: &SchemaRef| -> Result<_> {
1296+
let (l, r) = (col(left, schema)?, col(right, schema)?);
1297+
Ok([
1298+
binary(Arc::clone(&l), Operator::Plus, Arc::clone(&r), schema)?,
1299+
binary(Arc::clone(&l), Operator::Plus, lit(1), schema)?,
1300+
binary(Arc::clone(&r), Operator::Plus, lit(1), schema)?,
1301+
binary(l, Operator::Multiply, r, schema)?,
1302+
])
1303+
};
1304+
let [sum, left_plus_1, right_plus_1, product] = exprs("a", "b", &schema)?;
1305+
let mut group = EquivalenceGroup::default();
1306+
group.add_equal_conditions(sum, left_plus_1);
1307+
group.add_equal_conditions(right_plus_1, product);
1308+
let mapping = [
1309+
(
1310+
col("a", &schema)?,
1311+
vec![(col("x", &projected_schema)?, 0)].into(),
1312+
),
1313+
(
1314+
col("b", &schema)?,
1315+
vec![(col("y", &projected_schema)?, 1)].into(),
1316+
),
1317+
]
1318+
.into_iter()
1319+
.collect::<ProjectionMapping>();
1320+
1321+
let projected = group.project(&mapping);
1322+
1323+
let [sum, left_plus_1, right_plus_1, product] =
1324+
exprs("x", "y", &projected_schema)?;
1325+
assert_eq!(projected.len(), 2);
1326+
assert!(
1327+
projected
1328+
.normalize_expr(sum)
1329+
.eq(&projected.normalize_expr(left_plus_1))
1330+
);
1331+
assert!(
1332+
projected
1333+
.normalize_expr(right_plus_1)
1334+
.eq(&projected.normalize_expr(product))
1335+
);
1336+
1337+
Ok(())
1338+
}
1339+
12601340
/// A constant on the right side of a join stays constant in the join
12611341
/// output, unless unmatched rows pad the right side with NULLs.
12621342
/// <https://github.com/apache/datafusion/issues/26283>

0 commit comments

Comments
 (0)