datafusion-match-recognize 0.55.0

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.

//! `branch-55` `EnsureRequirements` compatibility wrapper.
//!
//! DataFusion 55.3's built-in `EnsureRequirements` runs a `sort_pushdown` pass
//! that lacks DataFusion 56 PR #26118 (proving custom-operator sort pushdown
//! validity) and PR #27331 (`LimitBehavior` fetch-pushdown guards and
//! preserving fetches above already-ordered operators).
//!
//! For plans that do not contain a `MATCH_RECOGNIZE` operator, this wrapper
//! delegates straight to stock `EnsureRequirements`. For plans containing
//! `MATCH_RECOGNIZE`, it executes DataFusion 55.3's exact `EnsureRequirements`
//! pipeline with the backported `sort_pushdown` pass in Phase 3c.

use std::sync::Arc;

use datafusion::execution::SessionStateBuilder;
use datafusion::physical_optimizer::PhysicalOptimizerRule;
use datafusion::physical_optimizer::ensure_requirements::EnsureRequirements;
use datafusion::physical_optimizer::ensure_requirements::enforce_distribution::{
    DistributionContext, PlanWithKeyRequirements, adjust_input_keys_ordering,
    ensure_distribution, reorder_join_keys_to_inputs,
};
use datafusion::physical_optimizer::ensure_requirements::enforce_sorting::replace_with_order_preserving_variants::{
    OrderPreservationContext, replace_with_order_preserving_variants,
};
use datafusion::physical_optimizer::ensure_requirements::enforce_sorting::{
    PlanWithCorrespondingCoalescePartitions, PlanWithCorrespondingSort, ensure_sorting,
    parallelize_sorts, replace_with_partial_sort,
};
use datafusion::common::Result;
use datafusion::common::config::ConfigOptions;
use datafusion::common::tree_node::{Transformed, TransformedResult, TreeNode};
use datafusion::physical_plan::ExecutionPlan;

use super::sort_pushdown::{SortPushDown, assign_initial_requirements, pushdown_sorts};
use crate::execution::physical::is_match_recognize_exec;

/// Drop-in replacement for DataFusion 55.3's [`EnsureRequirements`] rule that
/// runs the backported DataFusion 56 `sort_pushdown` pass on plans containing
/// `MATCH_RECOGNIZE`.
#[derive(Default, Debug)]
pub(crate) struct Branch55EnsureRequirements {}

impl Branch55EnsureRequirements {
    pub(crate) fn new() -> Self {
        Self {}
    }
}

impl PhysicalOptimizerRule for Branch55EnsureRequirements {
    fn optimize(
        &self,
        plan: Arc<dyn ExecutionPlan>,
        config: &ConfigOptions,
    ) -> Result<Arc<dyn ExecutionPlan>> {
        if !plan.exists(|node| Ok(is_match_recognize_exec(node.as_ref())))? {
            return EnsureRequirements::new().optimize(plan, config);
        }

        // Phase 1: Join key reordering (top-down, from EnforceDistribution)
        let plan = if config.optimizer.top_down_join_key_reordering {
            let ctx = PlanWithKeyRequirements::new_default(plan);
            ctx.transform_down(adjust_input_keys_ordering).data()?.plan
        } else {
            plan.transform_up(|p| Ok(Transformed::yes(reorder_join_keys_to_inputs(p)?)))
                .data()?
        };

        // Phase 2a: Distribution enforcement (bottom-up)
        let dist_ctx = DistributionContext::new_default(plan);
        let dist_ctx = dist_ctx
            .transform_up(|ctx| ensure_distribution(ctx, config))
            .data()?;

        // Phase 2b: Sorting enforcement (bottom-up) on distribution-fixed plan
        let sort_ctx = PlanWithCorrespondingSort::new_default(dist_ctx.plan);
        let sort_ctx = sort_ctx.transform_up(ensure_sorting)?.data;

        // Phase 3a: Parallelize sorts (Coalesce+Sort -> SPM+Sort)
        let plan = if config.optimizer.repartition_sorts {
            let ctx = PlanWithCorrespondingCoalescePartitions::new_default(sort_ctx.plan);
            ctx.transform_up(parallelize_sorts).data()?.plan
        } else {
            sort_ctx.plan
        };

        // Phase 3b: Order-preserving variants
        let ctx = OrderPreservationContext::new_default(plan);
        let plan = ctx
            .transform_up(|c| {
                replace_with_order_preserving_variants(c, false, true, config)
            })
            .data()?
            .plan;

        // Phase 3c: Backported DataFusion 56 sort pushdown (PR #26118 & #27331)
        let mut sort_pushdown = SortPushDown::new_default(plan);
        assign_initial_requirements(&mut sort_pushdown);
        let adjusted = pushdown_sorts(sort_pushdown)?;

        // Phase 3d: Partial sort
        adjusted
            .plan
            .transform_up(|p| Ok(Transformed::yes(replace_with_partial_sort(p)?)))
            .data()
    }

    fn name(&self) -> &str {
        "EnsureRequirements"
    }

    fn schema_check(&self) -> bool {
        true
    }
}

/// Replace any `"EnsureRequirements"` rule configured on `builder` with
/// [`Branch55EnsureRequirements`], keeping rule ordering and any extra rules
/// added via `with_physical_optimizer_rule` intact.
pub(crate) fn install_ensure_requirements_workaround(
    mut builder: SessionStateBuilder,
) -> SessionStateBuilder {
    let mut optimizers = builder.physical_optimizers().take().unwrap_or_default();
    for rule in &mut optimizers.rules {
        if rule.name() == "EnsureRequirements" {
            *rule = Arc::new(Branch55EnsureRequirements::new());
        }
    }
    builder.with_physical_optimizer_rules(optimizers.rules)
}

#[cfg(all(test, feature = "sql"))]
mod tests {
    use datafusion::arrow::array::{Array, Int64Array};
    use datafusion::common::Result;
    use datafusion::common::tree_node::TreeNode;
    use datafusion::execution::SessionStateBuilder;
    use datafusion::prelude::SessionConfig;

    use crate::execution::physical::is_match_recognize_exec;
    use crate::new_match_recognize_context;

    #[tokio::test]
    async fn outer_order_by_measure_is_not_pushed_below_match_recognize() -> Result<()> {
        let ctx = new_match_recognize_context(
            SessionStateBuilder::new()
                .with_default_features()
                .with_config(SessionConfig::new().with_target_partitions(2)),
        )?;
        let sql = "WITH t(seq, v) AS (VALUES (1, 30), (2, 10), (3, 20))
            SELECT last_v FROM t MATCH_RECOGNIZE (
                MEASURES LAST(A.v) AS last_v
                ONE ROW PER MATCH
                PATTERN (A) DEFINE A AS TRUE
            )
            ORDER BY last_v ASC";
        let batches = ctx.sql(sql).await?.collect().await?;
        let values: Vec<Option<i64>> = batches
            .iter()
            .flat_map(|batch| {
                let col = batch
                    .column(0)
                    .as_any()
                    .downcast_ref::<Int64Array>()
                    .expect("int64 output column");
                (0..col.len()).map(|i| (!col.is_null(i)).then(|| col.value(i)))
            })
            .collect();
        assert_eq!(values, vec![Some(10), Some(20), Some(30)]);
        Ok(())
    }

    #[tokio::test]
    async fn outer_order_by_limit_is_not_pushed_below_match_recognize() -> Result<()> {
        let ctx = new_match_recognize_context(
            SessionStateBuilder::new()
                .with_default_features()
                .with_config(SessionConfig::new().with_target_partitions(2)),
        )?;
        let sql = "WITH t(k, seq, v) AS (
                VALUES
                    (1, 1, 10), (1, 2, 20), (1, 3, 30),
                    (2, 1, 10), (2, 2, 20), (2, 3, 30),
                    (3, 1, 10), (3, 2, 20), (3, 3, 30)
            )
            SELECT k FROM t MATCH_RECOGNIZE (
                PARTITION BY k
                ORDER BY seq
                ONE ROW PER MATCH
                PATTERN (A+ B)
                DEFINE A AS v < 30, B AS v = 30
            )
            ORDER BY k
            LIMIT 2";
        let plan = ctx.sql(sql).await?.create_physical_plan().await?;
        // Ensure no Limit/fetch was pushed inside the matcher's input subtree.
        let mut matcher_input_has_fetch = false;
        plan.apply(|node| {
            if is_match_recognize_exec(node.as_ref()) {
                for child in node.children() {
                    if child.exists(|desc| Ok(desc.fetch().is_some()))? {
                        matcher_input_has_fetch = true;
                    }
                }
            }
            Ok(datafusion::common::tree_node::TreeNodeRecursion::Continue)
        })?;
        assert!(
            !matcher_input_has_fetch,
            "fetch must not be pushed below MATCH_RECOGNIZE:\n{}",
            datafusion::physical_plan::displayable(plan.as_ref()).indent(true)
        );

        let batches = datafusion::physical_plan::collect(plan, ctx.task_ctx()).await?;
        let values: Vec<i64> = batches
            .iter()
            .flat_map(|batch| {
                let col = batch
                    .column(0)
                    .as_any()
                    .downcast_ref::<Int64Array>()
                    .expect("int64 output column");
                (0..col.len()).map(|i| col.value(i))
            })
            .collect();
        assert_eq!(values, vec![1, 2]);
        Ok(())
    }

    #[tokio::test]
    async fn non_matcher_plan_preserves_rule_name_and_executes_via_fast_path()
    -> Result<()> {
        let ctx = new_match_recognize_context(
            SessionStateBuilder::new()
                .with_default_features()
                .with_config(SessionConfig::new().with_target_partitions(2)),
        )?;
        let state = ctx.state();
        let rule_names: Vec<&str> = state
            .physical_optimizers()
            .iter()
            .map(|r| r.name())
            .collect();
        assert_eq!(
            rule_names
                .iter()
                .filter(|&&n| n == "EnsureRequirements")
                .count(),
            1
        );
        let batches = ctx
            .sql("SELECT * FROM (VALUES (3), (1), (2)) AS t(x) ORDER BY x LIMIT 2")
            .await?
            .collect()
            .await?;
        let values: Vec<i64> = batches
            .iter()
            .flat_map(|batch| {
                let col = batch
                    .column(0)
                    .as_any()
                    .downcast_ref::<Int64Array>()
                    .expect("int64 output column");
                (0..col.len()).map(|i| col.value(i))
            })
            .collect();
        assert_eq!(values, vec![1, 2]);
        Ok(())
    }
}