datafusion-match-recognize 0.56.1

SQL MATCH_RECOGNIZE row-pattern matching for Apache 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.

//! Repair upstream DataFusion `56.0.0` requirement violations before matcher rewrites.
//!
//! Temporary workaround for [apache/datafusion#27318] (fixed upstream in
//! [apache/datafusion#27319]): in DataFusion `56.0.0`, `ProjectionPushdown`
//! can embed a column projection (for example into `FilterExec` or
//! `HashJoinExec`) that drops a CSE or extracted column while keeping its
//! underlying input columns. `EquivalenceGroup::project_expr_indirect` does
//! not fall back to another member of the dropped column's equivalence class,
//! losing constant or partitioning facts that `EnsureRequirements` relied on.
//!
//! For example, filtering a `CASE` partition key with a repeated subexpression
//! to a single constant (`WHERE bucket_id = 9190` or `WHERE skew_bucket = 9190`)
//! lets `EnsureRequirements` omit the constant partition key from `SortExec`,
//! and `ProjectionPushdown` then drops the CSE column inside `FilterExec`'s
//! embedded projection — causing DataFusion's final `SanityCheckPlan` check to
//! reject the plan.
//!
//! Because `match_recognize_physical` runs immediately before `SanityCheckPlan`,
//! repairing any already-broken plan on entry restores executable plans for
//! `MATCH_RECOGNIZE` queries without masking regressions introduced by our own
//! subsequent passes. Remove this workaround once a DataFusion release
//! containing `#27319` is adopted.
//!
//! [apache/datafusion#27318]: https://github.com/apache/datafusion/issues/27318
//! [apache/datafusion#27319]: https://github.com/apache/datafusion/pull/27319

use std::sync::Arc;

use super::rewrite_is_valid;
use crate::execution::physical::is_match_recognize_exec;
use datafusion::common::Result;
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::TreeNode;
use datafusion::physical_expr::Distribution;
use datafusion::physical_expr_common::sort_expr::OrderingRequirements;
use datafusion::physical_optimizer::ensure_coop::EnsureCooperative;
use datafusion::physical_optimizer::ensure_requirements::EnsureRequirements;
use datafusion::physical_optimizer::output_requirements::{
    OutputRequirementExec, OutputRequirements,
};
use datafusion::physical_optimizer::sanity_checker::input_requirements_hold;
use datafusion::physical_optimizer::{PhysicalOptimizerContext, PhysicalOptimizerRule};
use datafusion::physical_plan::execution_plan::replace_children_if_necessary;
use datafusion::physical_plan::operator_statistics::StatisticsRegistry;
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_plan::repartition::RepartitionExec;
use datafusion::physical_plan::scalar_subquery::ScalarSubqueryExec;
use datafusion::physical_plan::sorts::sort::SortExec;
use datafusion::physical_plan::sorts::sort_preserving_merge::SortPreservingMergeExec;
use datafusion::physical_plan::statistics::StatisticsContext;
use datafusion::physical_plan::{ExecutionPlan, ExecutionPlanProperties};

struct RepairContext<'a> {
    parent: &'a dyn PhysicalOptimizerContext,
    config: ConfigOptions,
}

impl PhysicalOptimizerContext for RepairContext<'_> {
    fn config_options(&self) -> &ConfigOptions {
        &self.config
    }

    fn statistics_registry(&self) -> Option<&StatisticsRegistry> {
        self.parent.statistics_registry()
    }

    fn statistics_context(&self) -> Option<&StatisticsContext> {
        self.parent.statistics_context()
    }
}

/// Repair at the outer sort through order-preserving wrappers, stopping before
/// matcher input requirements. DataFusion initializes sort-pushdown requirements
/// only at the root: placing OutputRequirementExec below a projection can lose
/// the global merge. Restore the wrappers after repair so hidden ORDER BY keys
/// still determine the rows consumed by OFFSET. Without an outer sort, retain
/// the root's ordering, single-partition, and fetch contract instead.
fn repair_root_requirements(
    plan: Arc<dyn ExecutionPlan>,
    repair: &impl Fn(Arc<dyn ExecutionPlan>) -> Result<Arc<dyn ExecutionPlan>>,
) -> Result<Arc<dyn ExecutionPlan>> {
    let mut cursor = Arc::clone(&plan);
    let mut ancestors: Vec<Arc<dyn ExecutionPlan>> = Vec::new();
    loop {
        if cursor.is::<SortPreservingMergeExec>() || cursor.is::<SortExec>() {
            // Capture the sort before a projection can hide its key. OFFSET
            // wrappers must consume this order even without a fetch limit.
            let mut repaired = repair(capture_requirements(cursor))?;
            for parent in ancestors.into_iter().rev() {
                let mut children: Vec<_> =
                    parent.children().into_iter().map(Arc::clone).collect();
                children[0] = repaired;
                // ScalarSubqueryExec's other children are independent plans.
                for child in children.iter_mut().skip(1) {
                    if !input_requirements_hold(child) {
                        *child = repair_root_requirements(Arc::clone(child), repair)?;
                    }
                }
                repaired = replace_children_if_necessary(parent, children)?;
            }
            // Reattaching a wrapper can invalidate its distribution or ordering
            // after inner repair removes an exchange. Repair with every ancestor
            // visible if the reconstructed tree no longer meets its contracts.
            return if rewrite_is_valid(&plan, &repaired) {
                Ok(repaired)
            } else {
                repair(capture_requirements(plan))
            };
        }
        // A matcher's input order is a matching requirement, not an outer
        // query order. Only detach wrappers without their own ordering or keyed
        // distribution requirements. Soft ordering (e.g. ordered aggregates) and
        // exchanges must remain visible to EnsureRequirements during repair.
        if is_match_recognize_exec(cursor.as_ref())
            || !(cursor.children().len() == 1 || cursor.is::<ScalarSubqueryExec>())
            || !cursor.maintains_input_order()[0]
            || cursor.required_input_ordering()[0].is_some()
            || !matches!(
                cursor
                    .input_distribution_requirements()
                    .child_distribution(0),
                Some(
                    Distribution::UnspecifiedDistribution | Distribution::SinglePartition
                )
            )
            || cursor.is::<RepartitionExec>()
        {
            return repair(capture_requirements(plan));
        }
        let child = Arc::clone(cursor.children()[0]);
        ancestors.push(cursor);
        cursor = child;
    }
}

fn capture_requirements(plan: Arc<dyn ExecutionPlan>) -> Arc<dyn ExecutionPlan> {
    let (ordering, dist, fetch) =
        if let Some(spm) = plan.downcast_ref::<SortPreservingMergeExec>() {
            (
                Some(OrderingRequirements::from(spm.expr().clone())),
                Distribution::SinglePartition,
                spm.fetch(),
            )
        } else {
            let ordering = plan
                .downcast_ref::<SortExec>()
                .map(|sort| OrderingRequirements::from(sort.expr().clone()))
                .or_else(|| {
                    plan.output_ordering()
                        .cloned()
                        .map(OrderingRequirements::from)
                });
            let dist = if plan.output_partitioning().partition_count() == 1 {
                Distribution::SinglePartition
            } else {
                Distribution::UnspecifiedDistribution
            };
            let fetch = root_fetch(plan.as_ref());
            (ordering, dist, fetch)
        };
    Arc::new(OutputRequirementExec::new(plan, ordering, dist, fetch))
}

/// Walk through 1-to-1 `ProjectionExec` wrappers to preserve a root fetch cap.
fn root_fetch(mut plan: &dyn ExecutionPlan) -> Option<usize> {
    loop {
        if let Some(fetch) = plan.fetch() {
            return Some(fetch);
        }
        let projection = plan.downcast_ref::<ProjectionExec>()?;
        plan = projection.input().as_ref();
    }
}

pub(super) fn optimize(
    plan: Arc<dyn ExecutionPlan>,
    context: &dyn PhysicalOptimizerContext,
) -> Result<Arc<dyn ExecutionPlan>> {
    // Only inspect plans containing MATCH_RECOGNIZE, and skip all work when
    // DataFusion's preceding rules already left requirements satisfied.
    if !plan.exists(|node| Ok(is_match_recognize_exec(node.as_ref())))?
        || input_requirements_hold(&plan)
    {
        return Ok(plan);
    }

    // Repair only: disable round-robin shuffles and scan re-splitting so
    // repair adds only missing sorts/repartitions without splitting a limit
    // or fetch input (mirroring apache/datafusion#27648).
    let mut config = context.config_options().clone();
    config.optimizer.enable_round_robin_repartition = false;
    config.optimizer.repartition_file_scans = false;
    let repair_context = RepairContext {
        parent: context,
        config,
    };

    let repaired = repair_root_requirements(plan, &|wrapped| {
        let repaired =
            EnsureRequirements::new().optimize_with_context(wrapped, &repair_context)?;
        OutputRequirements::new_remove_mode()
            .optimize(repaired, repair_context.config_options())
    })?;
    EnsureCooperative::new().optimize(repaired, repair_context.config_options())
}

#[cfg(all(test, feature = "sql"))]
mod tests;