use std::borrow::Borrow;
use std::sync::Arc;
use datafusion::arrow::compute::SortOptions;
use datafusion::arrow::datatypes::SchemaRef;
use datafusion::common::{Result, exec_err};
use datafusion::physical_expr::equivalence::{EquivalenceGroup, ProjectionMapping};
use datafusion::physical_expr::expressions::{Column, col};
use datafusion::physical_expr::{EquivalenceProperties, PhysicalExpr};
use datafusion::physical_expr_common::physical_expr::is_volatile;
use datafusion::physical_expr_common::sort_expr::{
LexOrdering, LexRequirement, OrderingRequirements, PhysicalSortExpr,
PhysicalSortRequirement,
};
use datafusion::physical_plan::execution_plan::{
Boundedness, EmissionType, PlanProperties,
};
use datafusion::physical_plan::{ExecutionPlan, ExecutionPlanProperties, Partitioning};
use crate::core::{
EmptyMatchesMode, MatchMetadataColumn, MatchRecognizeOutputSpec, RowsPerMatch,
};
use crate::execution::physical::exec::PartitionRetention;
use datafusion::physical_plan::windows::get_ordered_partition_by_indices;
pub(super) fn ordered_partition_by_indices(
partition_by: &[Arc<dyn PhysicalExpr>],
input: &Arc<dyn ExecutionPlan>,
) -> Result<Vec<usize>> {
let indices = get_ordered_partition_by_indices(partition_by, input)?;
if indices.len() < partition_by.len()
&& input
.equivalence_properties()
.ordering_satisfy_requirement(
partition_by
.iter()
.map(|expr| PhysicalSortRequirement::new(Arc::clone(expr), None)),
)?
{
return Ok((0..partition_by.len()).collect());
}
Ok(indices)
}
pub(super) fn get_partition_by_sort_exprs(
input: &Arc<dyn ExecutionPlan>,
partition_by_exprs: &[Arc<dyn PhysicalExpr>],
ordered_partition_by_indices: &[usize],
) -> Result<Vec<PhysicalSortExpr>> {
let ordered_partition_exprs = ordered_partition_by_indices
.iter()
.map(|idx| Arc::clone(&partition_by_exprs[*idx]))
.collect::<Vec<_>>();
assert!(ordered_partition_by_indices.len() <= partition_by_exprs.len());
let eq_properties = input.equivalence_properties();
let (ordering, _) =
eq_properties.find_longest_permutation(&ordered_partition_exprs)?;
if ordering.len() == ordered_partition_exprs.len() {
return Ok(ordering);
}
let mut requirements = Vec::with_capacity(ordered_partition_exprs.len());
let mut ordering = Vec::with_capacity(ordered_partition_exprs.len());
for expr in ordered_partition_exprs {
let mut found = false;
for options in [
SortOptions::new(false, true),
SortOptions::new(false, false),
SortOptions::new(true, true),
SortOptions::new(true, false),
] {
requirements.push(PhysicalSortRequirement::new(
Arc::clone(&expr),
Some(options),
));
if eq_properties.ordering_satisfy_requirement(requirements.iter().cloned())? {
ordering.push(PhysicalSortExpr::new(Arc::clone(&expr), options));
found = true;
break;
}
requirements.pop();
}
if !found {
return exec_err!(
"MATCH_RECOGNIZE could not derive sort expressions for every ordered PARTITION BY key"
);
}
}
Ok(ordering)
}
pub(super) fn calc_requirements<
T: Borrow<Arc<dyn PhysicalExpr>>,
S: Borrow<PhysicalSortExpr>,
>(
partition_by_exprs: impl IntoIterator<Item = T>,
orderby_sort_exprs: impl IntoIterator<Item = S>,
) -> Option<OrderingRequirements> {
let mut sort_reqs_with_partition = partition_by_exprs
.into_iter()
.map(|partition_by| {
PhysicalSortRequirement::new(Arc::clone(partition_by.borrow()), None)
})
.collect::<Vec<_>>();
for element in orderby_sort_exprs.into_iter() {
let PhysicalSortExpr { expr, options } = element.borrow();
let sort_req = PhysicalSortRequirement::new(Arc::clone(expr), Some(*options));
if !sort_reqs_with_partition.iter().any(|e| e.expr.eq(expr)) {
sort_reqs_with_partition.push(sort_req);
}
}
LexRequirement::new(sort_reqs_with_partition).map(OrderingRequirements::new)
}
struct OutputProjectionContext<'a> {
schema: &'a SchemaRef,
input: &'a Arc<dyn ExecutionPlan>,
passthrough_input_indices: &'a [usize],
mapping: ProjectionMapping,
}
impl<'a> OutputProjectionContext<'a> {
fn new(
schema: &'a SchemaRef,
input: &'a Arc<dyn ExecutionPlan>,
passthrough_input_indices: &'a [usize],
) -> Result<Self> {
let mapping =
ProjectionMapping::from_indices(passthrough_input_indices, &input.schema())?;
Ok(Self {
schema,
input,
passthrough_input_indices,
mapping,
})
}
fn project_input_equivalence_properties(
&self,
maintains_input_order: bool,
preserves_input_uniqueness: bool,
) -> Result<EquivalenceProperties> {
let mut projected = self
.input
.equivalence_properties()
.project(&self.mapping, Arc::clone(self.schema));
if !maintains_input_order {
projected.clear_orderings();
}
let constraints = if preserves_input_uniqueness {
self.input
.equivalence_properties()
.constraints()
.project(self.passthrough_input_indices)
.unwrap_or_default()
} else {
Default::default()
};
projected.set_constraints(constraints);
EquivalenceProperties::new(Arc::clone(self.schema)).extend(projected)
}
fn project_sort_exprs(
&self,
exprs: &[PhysicalSortExpr],
) -> Option<Vec<PhysicalSortExpr>> {
let input_eq_properties = self.input.equivalence_properties();
let mut result = Vec::with_capacity(exprs.len());
for se in exprs {
let proj_expr = input_eq_properties.project_expr(&se.expr, &self.mapping)?;
result.push(PhysicalSortExpr::new(proj_expr, se.options));
}
Some(result)
}
fn project_partition_exprs(
&self,
exprs: &[Arc<dyn PhysicalExpr>],
) -> Option<Vec<Arc<dyn PhysicalExpr>>> {
if exprs.iter().any(is_volatile) {
return None;
}
EquivalenceGroup::default()
.project_expressions(&self.mapping, exprs)
.collect()
}
}
pub(super) struct PhysicalPropertiesInput<'a> {
pub(super) input: &'a Arc<dyn ExecutionPlan>,
pub(super) schema: &'a SchemaRef,
pub(super) partition_by: &'a [Arc<dyn PhysicalExpr>],
pub(super) ordered_partition_by_indices: &'a [usize],
pub(super) order_by: &'a Option<LexOrdering>,
pub(super) output_spec: &'a MatchRecognizeOutputSpec,
pub(super) zero_output_navigation: bool,
pub(super) maintains_input_order: bool,
pub(super) preserves_input_uniqueness: bool,
pub(super) interleaves_logical_partitions: bool,
pub(super) ordered_unmatched: bool,
pub(super) rows_per_match: &'a RowsPerMatch,
pub(super) retention: PartitionRetention,
pub(super) bounded_match: bool,
pub(super) bypass_never_ordering: bool,
}
pub(super) struct PropertiesBuilder<'a> {
projection: OutputProjectionContext<'a>,
partition_by: &'a [Arc<dyn PhysicalExpr>],
ordered_partition_by_indices: &'a [usize],
order_by: &'a Option<LexOrdering>,
metadata_columns: &'a [MatchMetadataColumn],
maintains_input_order: bool,
preserves_input_uniqueness: bool,
preserves_partition_order: bool,
zero_output_navigation: bool,
rows_per_match: &'a RowsPerMatch,
retention: PartitionRetention,
bounded_match: bool,
}
impl<'a> PropertiesBuilder<'a> {
pub(super) fn try_new(input: PhysicalPropertiesInput<'a>) -> Result<Self> {
let preserves_partition_order = !input.bypass_never_ordering
&& (input.ordered_unmatched
|| !matches!(
input.rows_per_match,
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
))
&& (input.partition_by.is_empty() || !input.interleaves_logical_partitions);
let projection = OutputProjectionContext::new(
input.schema,
input.input,
input.output_spec.passthrough_input_indices(),
)?;
Ok(Self {
projection,
partition_by: input.partition_by,
ordered_partition_by_indices: input.ordered_partition_by_indices,
order_by: input.order_by,
metadata_columns: input.output_spec.metadata_columns(),
maintains_input_order: input.maintains_input_order
&& preserves_partition_order,
preserves_input_uniqueness: input.preserves_input_uniqueness,
preserves_partition_order,
zero_output_navigation: input.zero_output_navigation,
rows_per_match: input.rows_per_match,
retention: input.retention,
bounded_match: input.bounded_match,
})
}
pub(super) fn maintains_input_order(&self) -> bool {
self.maintains_input_order
}
pub(super) fn compute(&self) -> Result<PlanProperties> {
let eq_properties = self.mr_equivalence_properties()?;
let output_partitioning = self.compute_output_partitioning();
let input = self.projection.input;
let boundary_only =
self.retention == PartitionRetention::LogicalPartitionBoundaryOnly;
let emission = if self.partition_by.is_empty() && boundary_only {
EmissionType::Final
} else {
input.pipeline_behavior()
};
let boundedness = match input.boundedness() {
Boundedness::Bounded => Boundedness::Bounded,
Boundedness::Unbounded {
requires_infinite_memory,
} => Boundedness::Unbounded {
requires_infinite_memory: requires_infinite_memory
|| boundary_only
|| !self.bounded_match
|| matches!(
self.rows_per_match,
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
),
},
};
Ok(PlanProperties::new(
eq_properties,
output_partitioning,
emission,
boundedness,
))
}
fn compute_output_partitioning(&self) -> Partitioning {
match self.projection.input.output_partitioning() {
Partitioning::Hash(input_exprs, n) => self
.projection
.project_partition_exprs(input_exprs)
.map_or(Partitioning::UnknownPartitioning(*n), |exprs| {
Partitioning::Hash(exprs, *n)
}),
Partitioning::Range(range) => {
let exprs = range
.ordering()
.iter()
.map(|sort| Arc::clone(&sort.expr))
.collect::<Vec<_>>();
self.projection
.project_partition_exprs(&exprs)
.and_then(|exprs| range.adapt(&exprs, self.projection.schema))
.map_or(
Partitioning::UnknownPartitioning(range.partition_count()),
Partitioning::Range,
)
}
other => other.clone(),
}
}
fn mr_equivalence_properties(&self) -> Result<EquivalenceProperties> {
let mut eq_properties = self.projection.project_input_equivalence_properties(
self.maintains_input_order,
self.preserves_input_uniqueness,
)?;
if !self.preserves_partition_order {
return Ok(eq_properties);
}
if self.ordered_partition_by_indices.len() != self.partition_by.len() {
return Ok(eq_properties);
}
let partition_prefix_in = get_partition_by_sort_exprs(
self.projection.input,
self.partition_by,
self.ordered_partition_by_indices,
)?;
let Some(partition_prefix) =
self.projection.project_sort_exprs(&partition_prefix_in)
else {
return Ok(eq_properties);
};
let mut suffix_orderings = self.compute_suffix_orderings()?;
if suffix_orderings.is_empty() && !partition_prefix.is_empty() {
suffix_orderings.push(Vec::new());
}
for tail in suffix_orderings {
let mut full: Vec<PhysicalSortExpr> =
Vec::with_capacity(partition_prefix.len() + tail.len());
full.extend(partition_prefix.iter().cloned());
full.extend(tail);
if !full.is_empty() {
eq_properties.add_ordering(full);
}
}
Ok(eq_properties)
}
fn compute_suffix_orderings(&self) -> Result<Vec<Vec<PhysicalSortExpr>>> {
let mut suffix_orderings: Vec<Vec<PhysicalSortExpr>> = Vec::new();
if self.maintains_input_order
&& let Some(lex) = self.order_by
&& let Some(projected) = self.projection.project_sort_exprs(lex.as_ref())
{
suffix_orderings.push(projected);
}
if let Some(meta_suffix) = Self::compute_metadata_suffix(
self.projection.schema,
self.metadata_columns,
self.rows_per_match,
)? {
if self.zero_output_navigation
&& matches!(self.rows_per_match, RowsPerMatch::AllRows(_))
&& let Some(order) = self.order_by
{
let mut within_match = vec![meta_suffix[0].clone()];
for key in order.iter() {
let Some(column) = key.expr.downcast_ref::<Column>() else {
break;
};
let Some(slot) = self
.projection
.passthrough_input_indices
.iter()
.position(|index| *index == column.index())
else {
break;
};
let name = self.projection.schema.field(slot).name();
within_match.push(PhysicalSortExpr::new(
Arc::new(Column::new(name, slot)),
key.options,
));
}
if within_match.len() > 1 {
suffix_orderings.push(within_match);
}
}
suffix_orderings.push(meta_suffix);
}
Ok(suffix_orderings)
}
fn compute_metadata_suffix(
schema: &SchemaRef,
metadata_columns: &[MatchMetadataColumn],
rows_per_match: &RowsPerMatch,
) -> Result<Option<Vec<PhysicalSortExpr>>> {
if matches!(
rows_per_match,
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
) || !metadata_columns.contains(&MatchMetadataColumn::MatchNumber)
{
return Ok(None);
}
let sort = |column: MatchMetadataColumn| -> Result<PhysicalSortExpr> {
Ok(PhysicalSortExpr::new_default(col(column.as_ref(), schema)?).nulls_last())
};
let mut suffix = vec![sort(MatchMetadataColumn::MatchNumber)?];
if metadata_columns.contains(&MatchMetadataColumn::MatchSequenceNumber) {
suffix.push(sort(MatchMetadataColumn::MatchSequenceNumber)?);
}
Ok(Some(suffix))
}
}
#[cfg(test)]
mod tests {
use super::*;
use datafusion::arrow::compute::SortOptions;
use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::common::ScalarValue;
use datafusion::logical_expr::Operator;
use datafusion::physical_expr::{
RangePartitioning, SplitPoint,
expressions::{BinaryExpr, Column},
};
use datafusion::physical_plan::placeholder_row::PlaceholderRowExec;
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_plan::repartition::RepartitionExec;
use datafusion::physical_plan::sorts::sort::SortExec;
fn input_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("a", DataType::Int32, true),
Field::new("b", DataType::Int32, true),
Field::new("ts", DataType::Int32, true),
]))
}
fn input_columns(
input: &Arc<dyn ExecutionPlan>,
indices: &[usize],
) -> Vec<Arc<dyn PhysicalExpr>> {
indices
.iter()
.map(|&index| {
Arc::new(Column::new(input.schema().field(index).name(), index))
as Arc<dyn PhysicalExpr>
})
.collect()
}
fn output_properties(
input: &Arc<dyn ExecutionPlan>,
partition_indices: &[usize],
passthrough: &[usize],
order_by: Option<LexOrdering>,
metadata: Vec<MatchMetadataColumn>,
mode: RowsPerMatch,
) -> Result<PlanProperties> {
let mut fields = passthrough
.iter()
.map(|&index| input.schema().field(index).clone())
.collect::<Vec<_>>();
fields.extend(
metadata
.iter()
.map(|column| Field::new(column.as_ref(), column.data_type(), false)),
);
let schema = Arc::new(Schema::new(fields));
let spec = MatchRecognizeOutputSpec::new(passthrough.to_vec(), metadata, vec![]);
let partition_by = input_columns(input, partition_indices);
let ordered_indices = ordered_partition_by_indices(&partition_by, input)?;
PropertiesBuilder::try_new(PhysicalPropertiesInput {
input,
schema: &schema,
partition_by: &partition_by,
ordered_partition_by_indices: &ordered_indices,
order_by: &order_by,
output_spec: &spec,
zero_output_navigation: spec.navigation_offsets().is_zero(),
maintains_input_order: true,
preserves_input_uniqueness: true,
interleaves_logical_partitions: false,
ordered_unmatched: false,
rows_per_match: &mode,
retention: PartitionRetention::ThresholdSafe,
bounded_match: true,
bypass_never_ordering: false,
})?
.compute()
}
fn sorted_input(indices: &[usize]) -> Arc<dyn ExecutionPlan> {
let input: Arc<dyn ExecutionPlan> =
Arc::new(PlaceholderRowExec::new(input_schema()));
let ordering = LexOrdering::new(
input_columns(&input, indices)
.into_iter()
.map(PhysicalSortExpr::new_default),
)
.unwrap();
Arc::new(SortExec::new(ordering, input))
}
fn output_sort(properties: &PlanProperties, name: &str) -> Result<PhysicalSortExpr> {
Ok(PhysicalSortExpr::new_default(col(
name,
properties.eq_properties.schema(),
)?))
}
fn ordering_catalogue(
properties: &PlanProperties,
) -> Vec<Vec<(String, usize, bool, bool)>> {
let mut orderings = properties
.eq_properties
.oeq_class()
.iter()
.map(|ordering| {
ordering
.iter()
.map(|sort| {
let column = sort
.expr
.downcast_ref::<Column>()
.expect("test_case columns");
(
column.name().to_owned(),
column.index(),
sort.options.descending,
sort.options.nulls_first,
)
})
.collect()
})
.collect::<Vec<_>>();
orderings.sort();
orderings
}
fn create_test_schema() -> SchemaRef {
Arc::new(Schema::new(vec![
Field::new("a", DataType::Int32, true),
Field::new("b", DataType::Int32, true),
Field::new(
MatchMetadataColumn::MatchNumber.as_ref(),
DataType::Int32,
true,
),
]))
}
#[test]
fn constraint_satisfied_partition_keys_are_all_retained() -> Result<()> {
use datafusion::common::{Constraint, Constraints};
use datafusion::datasource::{
memory::MemorySourceConfig, source::DataSourceExec,
};
let schema = input_schema();
let source = MemorySourceConfig::try_new(&[vec![]], Arc::clone(&schema), None)?;
let source: Arc<dyn ExecutionPlan> =
Arc::new(DataSourceExec::new(Arc::new(source)).with_constraints(
Constraints::new_unverified(vec![Constraint::PrimaryKey(vec![0])]),
));
let input: Arc<dyn ExecutionPlan> = Arc::new(SortExec::new(
LexOrdering::new([PhysicalSortExpr::new_default(col("a", &schema)?)])
.unwrap(),
source,
));
let partition_by = input_columns(&input, &[0, 1]);
assert_eq!(
get_ordered_partition_by_indices(&partition_by, &input)?,
vec![0]
);
let indices = ordered_partition_by_indices(&partition_by, &input)?;
assert_eq!(indices, vec![0, 1]);
let keys = get_partition_by_sort_exprs(&input, &partition_by, &indices)?;
assert_eq!(keys.len(), 2);
assert!(input.equivalence_properties().ordering_satisfy(keys)?);
Ok(())
}
#[test]
fn requirements_have_only_the_complete_partition_first_alternative() -> Result<()> {
let input = sorted_input(&[0, 1, 2]);
let partition_by = input_columns(&input, &[0, 1]);
let order_by = [PhysicalSortExpr::new_default(col("ts", &input.schema())?)];
let expected = LexRequirement::new([
PhysicalSortRequirement::new(Arc::clone(&partition_by[0]), None),
PhysicalSortRequirement::new(Arc::clone(&partition_by[1]), None),
PhysicalSortRequirement::from(order_by[0].clone()),
])
.unwrap();
assert_eq!(
calc_requirements(&partition_by, &order_by),
Some(OrderingRequirements::Hard(vec![expected])),
);
let duplicate = [PhysicalSortExpr::new_default(Arc::clone(&partition_by[0]))];
assert_eq!(
calc_requirements(&partition_by, &duplicate)
.unwrap()
.first()
.len(),
2
);
assert!(
calc_requirements(
&[] as &[Arc<dyn PhysicalExpr>],
&[] as &[PhysicalSortExpr]
)
.is_none()
);
Ok(())
}
#[test]
fn output_hash_uses_only_original_passthrough_columns() -> Result<()> {
for (hash, keys, passthrough, count, expected) in [
(&[0][..], &[0][..], &[0, 1][..], 4, Some(&[0][..])),
(&[0][..], &[0, 1][..], &[1, 0][..], 4, Some(&[1][..])),
(&[0, 1][..], &[0, 1][..], &[1, 0][..], 4, Some(&[1, 0][..])),
(&[0][..], &[0][..], &[1][..], 4, None),
(&[0, 1][..], &[0, 1][..], &[0][..], 4, None),
(&[1][..], &[][..], &[1, 0][..], 1, Some(&[0][..])),
(&[1][..], &[][..], &[0][..], 1, None),
(&[1][..], &[][..], &[1, 0][..], 4, Some(&[0][..])),
(&[1][..], &[0][..], &[1, 0][..], 4, Some(&[0][..])),
] {
let source: Arc<dyn ExecutionPlan> =
Arc::new(PlaceholderRowExec::new(input_schema()));
let input: Arc<dyn ExecutionPlan> = Arc::new(RepartitionExec::try_new(
Arc::clone(&source),
Partitioning::Hash(input_columns(&source, hash), count),
)?);
let properties = output_properties(
&input,
keys,
passthrough,
None,
vec![MatchMetadataColumn::MatchNumber],
RowsPerMatch::OneRow,
)?;
match (expected, &properties.partitioning) {
(Some(indices), Partitioning::Hash(exprs, n)) => {
let expected = indices
.iter()
.map(|&index| {
Arc::new(Column::new(
source.schema().field(passthrough[index]).name(),
index,
)) as Arc<dyn PhysicalExpr>
})
.collect::<Vec<_>>();
assert_eq!((*n, exprs), (count, &expected));
}
(None, Partitioning::UnknownPartitioning(n)) => {
assert_eq!(*n, count);
}
_ => panic!(
"unexpected hash projection: hash={hash:?}, keys={keys:?}, \
passthrough={passthrough:?}, result={:?}",
properties.partitioning
),
}
}
Ok(())
}
#[test]
fn output_partitioning_preserves_count_without_false_range_keys() -> Result<()> {
let source: Arc<dyn ExecutionPlan> =
Arc::new(PlaceholderRowExec::new(input_schema()));
let range = RangePartitioning::try_new(
LexOrdering::new([PhysicalSortExpr::new_default(col(
"b",
&source.schema(),
)?)])
.unwrap(),
vec![
SplitPoint::new(vec![ScalarValue::Int32(Some(10))]),
SplitPoint::new(vec![ScalarValue::Int32(Some(20))]),
],
)?;
for (partitioning, expected) in [
(Partitioning::Range(range), ("unknown", 3)),
(Partitioning::RoundRobinBatch(4), ("round-robin", 4)),
] {
let input: Arc<dyn ExecutionPlan> =
Arc::new(RepartitionExec::try_new(Arc::clone(&source), partitioning)?);
for keys in [&[][..], &[0][..]] {
let properties = output_properties(
&input,
keys,
&[0],
None,
vec![MatchMetadataColumn::MatchNumber],
RowsPerMatch::OneRow,
)?;
let actual = match properties.partitioning {
Partitioning::UnknownPartitioning(n) => ("unknown", n),
Partitioning::RoundRobinBatch(n) => ("round-robin", n),
other => panic!("unexpected projected partitioning: {other:?}"),
};
assert_eq!(actual, expected);
}
}
let input: Arc<dyn ExecutionPlan> =
Arc::new(PlaceholderRowExec::new(input_schema()).with_partitions(5));
let properties =
output_properties(&input, &[], &[1], None, vec![], RowsPerMatch::OneRow)?;
assert!(matches!(
properties.partitioning,
Partitioning::UnknownPartitioning(5)
));
Ok(())
}
#[test]
fn computed_partitioning_requires_every_original_leaf() -> Result<()> {
let source: Arc<dyn ExecutionPlan> =
Arc::new(PlaceholderRowExec::new(input_schema()));
let sum = |a, b| -> Arc<dyn PhysicalExpr> {
Arc::new(BinaryExpr::new(
Arc::new(Column::new("a", a)),
Operator::Plus,
Arc::new(Column::new("b", b)),
))
};
let expression = sum(0, 1);
let options = SortOptions::new(true, false);
let range = RangePartitioning::try_new(
LexOrdering::new([PhysicalSortExpr::new(Arc::clone(&expression), options)])
.unwrap(),
vec![SplitPoint::new(vec![ScalarValue::Int32(Some(10))])],
)?;
for partitioning in [
Partitioning::Hash(vec![Arc::clone(&expression)], 2),
Partitioning::Range(range.clone()),
] {
let input: Arc<dyn ExecutionPlan> =
Arc::new(RepartitionExec::try_new(Arc::clone(&source), partitioning)?);
for passthrough in [&[1, 0][..], &[0][..]] {
let properties = output_properties(
&input,
&[0, 1],
passthrough,
None,
vec![],
RowsPerMatch::OneRow,
)?;
if passthrough.len() == 1 {
assert!(matches!(
properties.partitioning,
Partitioning::UnknownPartitioning(2)
));
continue;
}
match properties.partitioning {
Partitioning::Hash(exprs, count) => {
assert_eq!(exprs, [sum(1, 0)]);
assert_eq!(count, 2);
}
Partitioning::Range(actual) => {
assert!(actual.ordering()[0].expr.eq(&sum(1, 0)));
assert_eq!(actual.ordering()[0].options, options);
assert_eq!(actual.split_points(), range.split_points());
}
other => panic!("computed partitioning lost: {other:?}"),
}
}
}
Ok(())
}
#[test]
fn computed_partitioning_does_not_re_evaluate_volatile_keys() -> Result<()> {
use datafusion::common::DFSchema;
use datafusion::logical_expr::{
Volatility, create_udf, lit,
physical_planning_context::PhysicalPlanningContext,
};
use datafusion::physical_expr::{
create_physical_expr, execution_props::ExecutionProps,
};
let source: Arc<dyn ExecutionPlan> =
Arc::new(PlaceholderRowExec::new(input_schema()));
let function = create_udf(
"volatile_key",
vec![DataType::Int32],
DataType::Int32,
Volatility::Volatile,
Arc::new(|args| Ok(args[0].clone())),
);
let expression = create_physical_expr(
&(function.call(vec![datafusion::logical_expr::col("a")]) + lit(1_i32)),
&DFSchema::try_from(source.schema().as_ref().clone())?,
&ExecutionProps::new(),
&PhysicalPlanningContext::default(),
)?;
let input: Arc<dyn ExecutionPlan> = Arc::new(RepartitionExec::try_new(
source,
Partitioning::Hash(vec![expression], 2),
)?);
let properties =
output_properties(&input, &[0], &[0], None, vec![], RowsPerMatch::OneRow)?;
assert!(matches!(
properties.partitioning,
Partitioning::UnknownPartitioning(2)
));
Ok(())
}
#[test]
fn output_range_remaps_complete_keys_and_retains_boundaries() -> Result<()> {
let source: Arc<dyn ExecutionPlan> =
Arc::new(PlaceholderRowExec::new(input_schema()));
let options = [SortOptions::new(false, true), SortOptions::new(true, false)];
let range = RangePartitioning::try_new_with_samples(
LexOrdering::new(
input_columns(&source, &[1, 0])
.into_iter()
.zip(options)
.map(|(expr, options)| PhysicalSortExpr::new(expr, options)),
)
.unwrap(),
(1..=5)
.map(|value| {
SplitPoint::new(vec![
ScalarValue::Int32(Some(value * 10)),
ScalarValue::Int32(Some(value)),
])
})
.collect(),
3,
)?;
let input: Arc<dyn ExecutionPlan> = Arc::new(RepartitionExec::try_new(
source,
Partitioning::Range(range.clone()),
)?);
for (passthrough, expected_indices) in [
(&[0, 1][..], Some([1, 0])),
(&[1, 0][..], Some([0, 1])),
(&[1][..], None),
] {
let properties = output_properties(
&input,
&[0, 1],
passthrough,
None,
vec![],
RowsPerMatch::OneRow,
)?;
if let Some(expected_indices) = expected_indices {
let Partitioning::Range(actual) = properties.partitioning else {
panic!("complete range keys lost: {passthrough:?}");
};
let [b, a] = expected_indices;
let expected = LexOrdering::new([
PhysicalSortExpr::new(Arc::new(Column::new("b", b)), options[0]),
PhysicalSortExpr::new(Arc::new(Column::new("a", a)), options[1]),
])
.unwrap();
assert_eq!(actual.ordering(), &expected);
assert_eq!(actual.samples(), range.samples());
assert_eq!(actual.split_points(), range.split_points());
assert_eq!(
(actual.partition_count(), actual.max_partition_count()),
(3, 6)
);
} else {
assert!(matches!(
properties.partitioning,
Partitioning::UnknownPartitioning(3)
));
}
}
Ok(())
}
#[test]
fn suffix_orderings_require_every_ordered_projected_partition_key() -> Result<()> {
for (ordering, keys, passthrough, child_prefix) in [
(&[0, 2][..], &[0][..], &[2][..], None),
(&[0, 1, 2][..], &[0, 1][..], &[0, 2][..], Some("a")),
(&[0][..], &[0, 1][..], &[0, 1, 2][..], Some("a")),
(&[2][..], &[0][..], &[0, 2][..], Some("ts")),
] {
let input = sorted_input(ordering);
let order_by = LexOrdering::new([PhysicalSortExpr::new_default(col(
"ts",
&input.schema(),
)?)]);
let properties = output_properties(
&input,
keys,
passthrough,
order_by,
vec![MatchMetadataColumn::MatchNumber],
RowsPerMatch::OneRow,
)?;
let mn = output_sort(&properties, MatchMetadataColumn::MatchNumber.as_ref())?
.nulls_last();
assert!(!properties.eq_properties.ordering_satisfy([mn.clone()])?);
if let Some(prefix) = child_prefix {
let prefix = output_sort(&properties, prefix)?;
assert!(
properties
.eq_properties
.ordering_satisfy([prefix.clone()])?
);
assert!(!properties.eq_properties.ordering_satisfy([prefix, mn])?);
} else {
assert!(
!properties
.eq_properties
.ordering_satisfy([output_sort(&properties, "ts")?,])?
);
}
if child_prefix == Some("a") {
assert!(!properties.eq_properties.ordering_satisfy([
output_sort(&properties, "a")?,
output_sort(&properties, "ts")?,
])?);
}
}
Ok(())
}
#[test]
fn complete_partition_ordering_preserves_options_and_metadata() -> Result<()> {
let source: Arc<dyn ExecutionPlan> =
Arc::new(PlaceholderRowExec::new(input_schema()));
let a = PhysicalSortExpr::new(
col("a", &source.schema())?,
SortOptions::new(true, false),
);
let b = PhysicalSortExpr::new(
col("b", &source.schema())?,
SortOptions::new(false, true),
);
let ts = PhysicalSortExpr::new_default(col("ts", &source.schema())?);
let input: Arc<dyn ExecutionPlan> = Arc::new(SortExec::new(
LexOrdering::new([b.clone(), a.clone(), ts.clone()]).unwrap(),
source,
));
for mode in [
RowsPerMatch::OneRow,
RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
] {
let properties = output_properties(
&input,
&[0, 1],
&[2, 0, 1],
LexOrdering::new([ts.clone()]),
vec![
MatchMetadataColumn::MatchNumber,
MatchMetadataColumn::MatchSequenceNumber,
],
mode.clone(),
)?;
let key = [("b".into(), 2, false, true), ("a".into(), 1, true, false)];
let number = ("__mr_match_number".into(), 3, false, false);
let sequence = ("__mr_match_sequence_number".into(), 4, false, false);
let timestamp = ("ts".into(), 0, false, true);
let with_key =
|suffix: Vec<_>| key.iter().cloned().chain(suffix).collect::<Vec<_>>();
let mut expected = vec![with_key(vec![number.clone(), sequence])];
if matches!(mode, RowsPerMatch::AllRows(_)) {
expected.push(with_key(vec![number, timestamp.clone()]));
}
expected.push(with_key(vec![timestamp]));
assert_eq!(ordering_catalogue(&properties), expected);
}
Ok(())
}
#[test]
fn equivalent_projected_key_keeps_complete_partition_ordering() -> Result<()> {
let source: Arc<dyn ExecutionPlan> =
Arc::new(PlaceholderRowExec::new(input_schema()));
let a = col("a", &source.schema())?;
let projected: Arc<dyn ExecutionPlan> = Arc::new(ProjectionExec::try_new(
vec![
(Arc::clone(&a), "a".to_string()),
(a, "b".to_string()),
(col("ts", &source.schema())?, "ts".to_string()),
],
source,
)?);
let input: Arc<dyn ExecutionPlan> = Arc::new(SortExec::new(
LexOrdering::new([
PhysicalSortExpr::new_default(col("a", &projected.schema())?),
PhysicalSortExpr::new_default(col("ts", &projected.schema())?),
])
.unwrap(),
projected,
));
let properties = output_properties(
&input,
&[0],
&[1, 2],
None,
vec![MatchMetadataColumn::MatchNumber],
RowsPerMatch::OneRow,
)?;
assert_eq!(
ordering_catalogue(&properties),
[
vec![
("b".into(), 0, false, true),
("__mr_match_number".into(), 2, false, false)
],
vec![("b".into(), 0, false, true), ("ts".into(), 1, false, true)],
]
);
Ok(())
}
#[test]
fn metadata_ordering_catalogue_requires_match_number_and_omits_unmatched_rows()
-> Result<()> {
let source: Arc<dyn ExecutionPlan> =
Arc::new(PlaceholderRowExec::new(input_schema()));
use MatchMetadataColumn::{
MatchNumber as Number, MatchSequenceNumber as Sequence,
};
for (mode, metadata, expected) in [
(RowsPerMatch::OneRow, vec![], vec![]),
(RowsPerMatch::OneRow, vec![Sequence], vec![]),
(
RowsPerMatch::OneRow,
vec![Number],
vec![vec![("__mr_match_number".into(), 1, false, false)]],
),
(
RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
vec![Number, Sequence],
vec![vec![
("__mr_match_number".into(), 1, false, false),
("__mr_match_sequence_number".into(), 2, false, false),
]],
),
(
RowsPerMatch::AllRows(EmptyMatchesMode::Show),
vec![Number, Sequence],
vec![vec![
("__mr_match_number".into(), 1, false, false),
("__mr_match_sequence_number".into(), 2, false, false),
]],
),
(
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched),
vec![Number, Sequence],
vec![],
),
] {
let properties = output_properties(&source, &[], &[0], None, metadata, mode)?;
assert_eq!(ordering_catalogue(&properties), expected);
}
Ok(())
}
#[test]
fn streaming_properties_follow_retention_match_bound_and_child() -> Result<()> {
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::physical_plan::streaming::StreamingTableExec;
use datafusion::physical_plan::test::TestPartitionStream;
let threshold = PartitionRetention::ThresholdSafe;
let boundary = PartitionRetention::LogicalPartitionBoundaryOnly;
let bounded = Boundedness::Bounded;
let streaming = Boundedness::Unbounded {
requires_infinite_memory: false,
};
let retained = Boundedness::Unbounded {
requires_infinite_memory: true,
};
for (
keyed,
retention,
bounded_match,
infinite,
final_child,
emission,
expected,
) in [
(
true,
threshold,
true,
false,
false,
EmissionType::Incremental,
bounded,
),
(
false,
threshold,
false,
false,
false,
EmissionType::Incremental,
bounded,
),
(
false,
boundary,
true,
false,
false,
EmissionType::Final,
bounded,
),
(
true,
boundary,
true,
false,
false,
EmissionType::Incremental,
bounded,
),
(
true,
threshold,
true,
true,
false,
EmissionType::Incremental,
streaming,
),
(
false,
threshold,
true,
true,
false,
EmissionType::Incremental,
streaming,
),
(
true,
threshold,
false,
true,
false,
EmissionType::Incremental,
retained,
),
(
false,
threshold,
false,
true,
false,
EmissionType::Incremental,
retained,
),
(
false,
boundary,
true,
true,
false,
EmissionType::Final,
retained,
),
(
true,
boundary,
true,
true,
false,
EmissionType::Incremental,
retained,
),
(
true,
threshold,
true,
false,
true,
EmissionType::Final,
bounded,
),
(
true,
threshold,
true,
true,
true,
EmissionType::Final,
retained,
),
] {
let schema = input_schema();
let source = Arc::new(TestPartitionStream::new_with_batches(vec![
RecordBatch::new_empty(Arc::clone(&schema)),
]));
let mut input: Arc<dyn ExecutionPlan> =
Arc::new(StreamingTableExec::try_new(
Arc::clone(&schema),
vec![source],
None,
[],
infinite,
None,
)?);
if final_child {
input = Arc::new(SortExec::new(
LexOrdering::new([PhysicalSortExpr::new_default(col("a", &schema)?)])
.unwrap(),
input,
));
}
let partition_by = input_columns(&input, if keyed { &[0] } else { &[] });
let spec = MatchRecognizeOutputSpec::new(vec![0, 1, 2], vec![], vec![]);
let ordered_indices = ordered_partition_by_indices(&partition_by, &input)?;
for rows_per_match in [
RowsPerMatch::OneRow,
RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched),
] {
let expected = if infinite
&& matches!(
rows_per_match,
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
) {
retained
} else {
expected
};
let properties = PropertiesBuilder::try_new(PhysicalPropertiesInput {
input: &input,
schema: &schema,
partition_by: &partition_by,
ordered_partition_by_indices: &ordered_indices,
order_by: &None,
output_spec: &spec,
zero_output_navigation: spec.navigation_offsets().is_zero(),
maintains_input_order: true,
preserves_input_uniqueness: true,
interleaves_logical_partitions: false,
ordered_unmatched: false,
rows_per_match: &rows_per_match,
retention,
bounded_match,
bypass_never_ordering: false,
})?
.compute()?;
assert_eq!(
(properties.emission_type, properties.boundedness),
(emission, expected),
"keyed={keyed}, retention={retention:?}, bounded_match={bounded_match}, infinite={infinite}, final_child={final_child}, rows_per_match={rows_per_match:?}",
);
}
}
Ok(())
}
#[test]
fn output_orderings_require_serial_partition_emission() -> Result<()> {
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_plan::sorts::sort::SortExec;
let schema = create_test_schema();
let a = col("a", &schema)?;
let b = col("b", &schema)?;
let projected: Arc<dyn ExecutionPlan> = Arc::new(ProjectionExec::try_new(
vec![
(Arc::clone(&a), "a".to_string()),
(Arc::clone(&a), "b".to_string()),
(
col(MatchMetadataColumn::MatchNumber.as_ref(), &schema)?,
MatchMetadataColumn::MatchNumber.as_ref().to_string(),
),
],
Arc::new(PlaceholderRowExec::new(Arc::clone(&schema))),
)?);
let input: Arc<dyn ExecutionPlan> = Arc::new(SortExec::new(
LexOrdering::new([PhysicalSortExpr::new_default(Arc::clone(&a))]).unwrap(),
projected,
));
let spec = MatchRecognizeOutputSpec::new(
vec![0, 1],
vec![MatchMetadataColumn::MatchNumber],
vec![],
);
let order_by = LexOrdering::new([PhysicalSortExpr::new_default(Arc::clone(&b))]);
for (mode, partitioned, interleaved, ordered) in [
(RowsPerMatch::OneRow, true, false, true),
(
RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched),
true,
false,
false,
),
(RowsPerMatch::OneRow, true, true, false),
(RowsPerMatch::OneRow, false, true, true),
] {
let partition_by = partitioned
.then(|| Arc::clone(&a))
.into_iter()
.collect::<Vec<_>>();
let ordered_indices = ordered_partition_by_indices(&partition_by, &input)?;
let builder = PropertiesBuilder::try_new(PhysicalPropertiesInput {
input: &input,
schema: &schema,
partition_by: &partition_by,
ordered_partition_by_indices: &ordered_indices,
order_by: &order_by,
output_spec: &spec,
zero_output_navigation: spec.navigation_offsets().is_zero(),
maintains_input_order: true,
preserves_input_uniqueness: true,
interleaves_logical_partitions: interleaved,
ordered_unmatched: false,
rows_per_match: &mode,
retention: PartitionRetention::ThresholdSafe,
bounded_match: true,
bypass_never_ordering: false,
})?;
assert_eq!(builder.maintains_input_order(), ordered);
let properties = builder.compute()?;
assert_eq!(!properties.eq_properties.oeq_class().is_empty(), ordered);
assert!(properties.eq_properties.eq_group().exprs_equal(&a, &b));
assert!(matches!(
properties.partitioning,
Partitioning::UnknownPartitioning(1)
));
}
Ok(())
}
}