datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for DataFusion
Documentation
// Licensed under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
//
// This product includes software developed at Datadog (https://www.datadoghq.com/) Copyright 2025-Present Datadog, Inc.

//! Preserve every observable ordering while replacing the sort of a keyed matcher.

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};

/// Collapse a redundant `1 -> RoundRobinBatch(N) -> [Filter/Projection]+ ->
/// Hash/Coalesce -> [SortExec]` round-trip between a 1-partition matcher or
/// streaming window and an outer `StreamingMatchWindowExec`.
///
/// Bottom-up `EnforceDistribution` can speculatively fan out a 1-partition
/// `FilterExec` (e.g., navigation buffer-row stripping) when upstream row
/// statistics are `Inexact`/`Absent`, forcing the immediately following
/// `StreamingMatchWindowExec` to re-hash and re-sort what was already grouped
/// and ordered on 1 partition.
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),
        )?;
    }
    // Partition contiguity alone does not preserve the direction/null order
    // observed by a projection or LIMIT above the window. The rebuilt stream
    // has one partition, so it also preserves a non-partition-preserving sort's
    // global ordering contract.
    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();
    // EnsureRequirements may have eliminated the SQL result's final ORDER BY
    // using this very matcher. Preserve any ordering still exposed at the root.
    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)| {
            // Every ordering demanded directly by a window, merge or grouped
            // aggregate survives. StreamingMatchWindowExec only needs contiguous
            // within-partition `(mn, seq)` order (which `Unordered` grouped
            // output preserves), so it does not by itself force cross-partition
            // `PartitionKeyOrder` when its input reaches the matcher solely
            // through the transparent chain accepted by
            // `input_uses_unordered_grouped_matcher`. Intervening exchanges
            // (such as an order-preserving RepartitionExec) keep
            // `required_input_ordering` intact, so preserve that requirement. A
            // projection/filter may carry an ancestor's ordering through several
            // levels without declaring its own, and a root projection may
            // project away an enforced ORDER BY key.
            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);
    }
    // Upstream partitioned windows feeding MATCH_RECOGNIZE often share its sort
    // boundary (e.g. CTE LAG/ROW_NUMBER before matching). Rewriting their sort
    // with PartitionKeyOrder preserves full EquivalenceProperties while replacing
    // O(N log N) multi-key sorting with hash-grouped per-partition sorting.
    if in_matcher_input {
        return Ok(window.rewrite_node(plan)?.data);
    }
    Ok(plan)
}

/// Whether `plan` reaches `MatchRecognizePatternExec` solely through the
/// transparent operator chain accepted by
/// `StreamingMatchWindowExec::input_uses_unordered_grouped_matcher`.
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
}

/// VALUES, CTEs and subqueries can rename or reorder columns immediately
/// after the enforced sort. Carry those aliases to the grouping input while
/// retaining the original tree if no rewrite applies.
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;