use std::sync::Arc;
use super::rewrite_is_valid;
use crate::config::MatchRecognizeConfig;
use crate::execution::physical::{
is_match_recognize_exec, match_recognize_grouped_order_rule,
running_window::StreamingMatchWindowExec,
};
use datafusion::physical_expr::expressions::{Column, Literal};
use datafusion::physical_expr::projection::update_expr;
use datafusion::physical_expr::{LexOrdering, PhysicalSortExpr};
#[cfg(all(test, feature = "sql"))]
use datafusion::physical_optimizer::sanity_checker::input_requirements_hold;
use datafusion::physical_plan::coalesce_partitions::CoalescePartitionsExec;
use datafusion::physical_plan::execution_plan::{
ChildrenPropertiesMode, ReplaceChildrenOptions, replace_children_if_necessary,
};
use datafusion::physical_plan::filter::FilterExec;
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_plan::repartition::RepartitionExec;
use datafusion::physical_plan::sorts::sort::SortExec;
use datafusion::physical_plan::union::UnionExec;
use datafusion::physical_plan::{
ExecutionPlan, ExecutionPlanProperties, LimitBehavior, Partitioning,
};
use datafusion_common::tree_node::{Transformed, TreeNode};
use datafusion_common::{Result, config::ConfigOptions};
use datafusion_hash_grouped_order::{GroupEmitOrder, HashGroupedOrderRule};
pub(super) fn collapse_roundrobin_window_roundtrip(
plan: Arc<dyn ExecutionPlan>,
) -> Result<Arc<dyn ExecutionPlan>> {
let original = Arc::clone(&plan);
let transformed = plan.transform_up(|node| {
if !node.is::<StreamingMatchWindowExec>() {
return Ok(Transformed::no(node));
}
let Some(rebuilt_input) = try_peel_roundtrip(node.children()[0])? else {
return Ok(Transformed::no(node));
};
let rebuilt = node.replace_children(
vec![rebuilt_input],
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)?;
Ok(Transformed::yes(rebuilt))
})?;
if transformed.transformed && rewrite_is_valid(&original, &transformed.data) {
Ok(transformed.data)
} else {
Ok(original)
}
}
fn try_peel_roundtrip(
input: &Arc<dyn ExecutionPlan>,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
let after_sort = match input.downcast_ref::<SortExec>() {
Some(sort) if sort.fetch().is_none() => sort.input(),
Some(_) => return Ok(None),
None => input,
};
let after_gather = if let Some(repart) = after_sort.downcast_ref::<RepartitionExec>()
&& matches!(
repart.partitioning(),
Partitioning::Hash(_, _) | Partitioning::Range(_)
) {
repart.input()
} else if let Some(coalesce) = after_sort.downcast_ref::<CoalescePartitionsExec>()
&& coalesce.fetch().is_none()
{
coalesce.input()
} else {
return Ok(None);
};
let mut chain: Vec<Arc<dyn ExecutionPlan>> = Vec::new();
let mut cursor = after_gather;
loop {
if let Some(proj) = cursor.downcast_ref::<ProjectionExec>() {
chain.push(Arc::clone(cursor));
cursor = proj.input();
} else if let Some(filter) = cursor.downcast_ref::<FilterExec>()
&& filter.fetch().is_none()
{
chain.push(Arc::clone(cursor));
cursor = filter.input();
} else {
break;
}
}
if chain.is_empty() {
return Ok(None);
}
let Some(rr) = cursor.downcast_ref::<RepartitionExec>() else {
return Ok(None);
};
if !matches!(rr.partitioning(), Partitioning::RoundRobinBatch(_)) {
return Ok(None);
}
let base = rr.input();
if base.output_partitioning().partition_count() != 1
|| !(is_match_recognize_exec(base.as_ref())
|| base.is::<StreamingMatchWindowExec>())
{
return Ok(None);
}
let mut rebuilt = Arc::clone(base);
for op in chain.into_iter().rev() {
rebuilt = op.replace_children(
vec![rebuilt],
ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
)?;
}
if let Some(sort) = input.downcast_ref::<SortExec>()
&& !rebuilt
.equivalence_properties()
.ordering_satisfy(sort.expr().clone())?
{
return Ok(None);
}
Ok(Some(rebuilt))
}
pub(super) fn optimize(
plan: Arc<dyn ExecutionPlan>,
config: &ConfigOptions,
) -> Result<Arc<dyn ExecutionPlan>> {
let settings = config.extensions.get::<MatchRecognizeConfig>();
if settings.is_some_and(|mr| mr.diagnostics.disable_hash_grouped_ordering) {
return Ok(plan);
}
let prune = !settings.is_some_and(|mr| {
mr.diagnostics.disable_pre_sort_partition_pruning
|| mr.diagnostics.disable_pattern_optimizer
});
let ordered =
match_recognize_grouped_order_rule(GroupEmitOrder::PartitionKeyOrder, prune);
let unordered = match_recognize_grouped_order_rule(GroupEmitOrder::Unordered, prune);
let window = HashGroupedOrderRule::default();
let keep = plan.output_ordering().is_some();
rewrite(plan, keep, true, false, &ordered, &unordered, &window)
}
fn rewrite(
plan: Arc<dyn ExecutionPlan>,
keep: bool,
root_chain: bool,
in_matcher_input: bool,
ordered: &HashGroupedOrderRule,
unordered: &HashGroupedOrderRule,
window: &HashGroupedOrderRule,
) -> Result<Arc<dyn ExecutionPlan>> {
let children = plan.children();
if children.is_empty() {
return Ok(plan);
}
let is_matcher = is_match_recognize_exec(plan.as_ref());
let child_in_matcher_input = in_matcher_input || is_matcher;
let required = plan.required_input_ordering();
let preserved = plan.maintains_input_order();
let observes_limit = plan.fetch().is_some()
|| matches!(
plan.limit_behavior(),
LimitBehavior::Limit { skip, fetch } if skip > 0 || fetch.is_some()
);
let union_ordered = plan.is::<UnionExec>() && plan.output_ordering().is_some();
let replacements = children
.into_iter()
.enumerate()
.map(|(i, child)| {
let child_preserves = preserved[i] || union_ordered;
let child_root_chain = root_chain && child_preserves;
let suppress_window_requirement = plan.is::<StreamingMatchWindowExec>()
&& reaches_matcher_transparently(child.as_ref());
let own_required = !suppress_window_requirement && required[i].is_some();
let observe = own_required
|| ((keep || observes_limit) && child_preserves)
|| (child_root_chain && child.output_ordering().is_some());
rewrite(
Arc::clone(child),
observe,
child_root_chain,
child_in_matcher_input,
ordered,
unordered,
window,
)
})
.collect::<Result<Vec<_>>>()?;
let plan = replace_children_if_necessary(plan, replacements)?;
if let Some(smw) = plan.downcast_ref::<StreamingMatchWindowExec>()
&& smw.input_uses_unordered_grouped_matcher()
{
return Ok(smw.with_unordered_grouped()?);
}
if is_matcher {
let rule = if keep { ordered } else { unordered };
if let Some(projected) = through_alias_projection(&plan)? {
let rewritten = rule.rewrite_node(projected)?;
if rewritten.transformed {
return Ok(rewritten.data);
}
}
return Ok(rule.rewrite_node(plan)?.data);
}
if in_matcher_input {
return Ok(window.rewrite_node(plan)?.data);
}
Ok(plan)
}
fn reaches_matcher_transparently(plan: &dyn ExecutionPlan) -> bool {
if is_match_recognize_exec(plan) {
return true;
}
if plan.is::<ProjectionExec>()
|| plan.is::<FilterExec>()
|| plan.is::<StreamingMatchWindowExec>()
{
return plan
.children()
.first()
.is_some_and(|child| reaches_matcher_transparently(child.as_ref()));
}
false
}
fn through_alias_projection(
plan: &Arc<dyn ExecutionPlan>,
) -> Result<Option<Arc<dyn ExecutionPlan>>> {
let input = plan.children()[0];
let Some(projection) = input.downcast_ref::<ProjectionExec>() else {
return Ok(None);
};
let Some(sort) = projection.input().downcast_ref::<SortExec>() else {
return Ok(None);
};
if sort.fetch().is_some()
|| !sort.preserve_partitioning()
&& sort.input().output_partitioning().partition_count() > 1
|| projection.expr().iter().any(|p| {
p.expr.downcast_ref::<Column>().is_none()
&& p.expr.downcast_ref::<Literal>().is_none()
})
{
return Ok(None);
}
let mut keys = Vec::with_capacity(sort.expr().len());
for key in sort.expr() {
let Some(expr) = update_expr(&key.expr, projection.expr(), false)? else {
return Ok(None);
};
keys.push(PhysicalSortExpr::new(expr, key.options));
}
let Some(ordering) = LexOrdering::new(keys) else {
return Ok(None);
};
let projected =
replace_children_if_necessary(Arc::clone(input), vec![Arc::clone(sort.input())])?;
let new_sort = SortExec::new(ordering, projected)
.with_preserve_partitioning(sort.preserve_partitioning());
replace_children_if_necessary(Arc::clone(plan), vec![Arc::new(new_sort)]).map(Some)
}
#[cfg(all(test, feature = "sql"))]
mod tests;