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` workaround for DataFusion 55's leaf-expression projection merge bug.
//!
//! In DataFusion 55.3 (`datafusion_optimizer::extract_leaf_expressions`),
//! `build_extraction_projection_impl` merges extracted leaf expressions (such as
//! struct field access `s['k']` or list indexing `a[1]`) into an existing child
//! `Projection` by checking only bare `Expr::Column` pass-throughs. When the
//! child `Projection` strips a table qualifier with a same-name alias (e.g.
//! `events.customer AS customer`, emitted by `MATCH_RECOGNIZE` output
//! finalization), DataFusion 55 appends `events.customer` beside `customer`,
//! failing `Projection::try_new` with `SchemaError::AmbiguousReference` (fixed
//! in DataFusion 56, apache/datafusion#25446).
//!
//! Wrapping `"extract_leaf_expressions"` and `"push_down_leaf_projections"` to
//! skip the rewrite on that exact `AmbiguousReference` lets `OptimizeProjections`
//! merge the projections cleanly in the same optimizer pass.

use std::sync::Arc;

use datafusion::common::tree_node::{Transformed, TreeNodeRecursion};
use datafusion::common::{DataFusionError, Result, SchemaError};
use datafusion::execution::SessionStateBuilder;
use datafusion::logical_expr::{Expr, LogicalPlan};
use datafusion::optimizer::{ApplyOrder, OptimizerConfig, OptimizerRule};

use crate::planning::logical::MatchRecognize;

#[derive(Debug)]
struct Branch55LeafProjectionGuard {
    inner: Arc<dyn OptimizerRule + Send + Sync>,
}

impl Branch55LeafProjectionGuard {
    fn new(inner: Arc<dyn OptimizerRule + Send + Sync>) -> Self {
        Self { inner }
    }
}

fn has_qualifier_stripping_alias(exprs: &[Expr]) -> bool {
    exprs.iter().any(|expr| {
        matches!(
            expr,
            Expr::Alias(alias)
                if alias.relation.is_none()
                    && matches!(
                        alias.expr.as_ref(),
                        Expr::Column(col)
                            if col.relation.is_some() && col.name == alias.name
                    )
        )
    })
}

fn contains_match_recognize_with_qualifier_strip(plan: &LogicalPlan) -> bool {
    let mut has_match_recognize = false;
    let mut has_qualifier_strip = false;
    let _ = plan.apply_with_subqueries(|node| {
        match node {
            LogicalPlan::Extension(ext) if ext.node.as_any().is::<MatchRecognize>() => {
                has_match_recognize = true;
            }
            LogicalPlan::Projection(proj)
                if !has_qualifier_strip && has_qualifier_stripping_alias(&proj.expr) =>
            {
                has_qualifier_strip = true;
            }
            _ => {}
        }
        Ok(if has_match_recognize && has_qualifier_strip {
            TreeNodeRecursion::Stop
        } else {
            TreeNodeRecursion::Continue
        })
    });
    has_match_recognize && has_qualifier_strip
}

fn is_ambiguous_reference(err: &DataFusionError) -> bool {
    matches!(
        err.find_root(),
        DataFusionError::SchemaError(schema_err, _)
            if matches!(schema_err.as_ref(), SchemaError::AmbiguousReference { .. })
    )
}

impl OptimizerRule for Branch55LeafProjectionGuard {
    fn name(&self) -> &str {
        self.inner.name()
    }

    fn apply_order(&self) -> Option<ApplyOrder> {
        self.inner.apply_order()
    }

    fn rewrite(
        &self,
        plan: LogicalPlan,
        config: &dyn OptimizerConfig,
    ) -> Result<Transformed<LogicalPlan>> {
        if !contains_match_recognize_with_qualifier_strip(&plan) {
            return self.inner.rewrite(plan, config);
        }
        let original = plan.clone();
        match self.inner.rewrite(plan, config) {
            Ok(transformed) => Ok(transformed),
            Err(err) if is_ambiguous_reference(&err) => Ok(Transformed::no(original)),
            Err(err) => Err(err),
        }
    }
}

/// Wrap DataFusion 55's `"extract_leaf_expressions"` and
/// `"push_down_leaf_projections"` logical rules on `builder` with
/// [`Branch55LeafProjectionGuard`], keeping rule ordering and any extra rules
/// added via `with_optimizer_rule` intact.
pub(crate) fn install_leaf_projection_workaround(
    mut builder: SessionStateBuilder,
) -> SessionStateBuilder {
    let mut optimizer = builder.optimizer().take().unwrap_or_default();
    for rule in &mut optimizer.rules {
        if matches!(
            rule.name(),
            "extract_leaf_expressions" | "push_down_leaf_projections"
        ) {
            *rule = Arc::new(Branch55LeafProjectionGuard::new(Arc::clone(rule)));
        }
    }
    builder.with_optimizer_rules(optimizer.rules)
}

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

    use crate::new_match_recognize_context;

    #[tokio::test]
    async fn leaf_expression_over_qualifier_stripped_match_recognize_executes()
    -> Result<()> {
        let ctx = new_match_recognize_context(
            SessionStateBuilder::new().with_default_features(),
        )?;
        let base_cte = "WITH order_events AS (
                SELECT 1 AS customer, 1 AS ord, 10 AS amount
                UNION ALL SELECT 1, 2, 15
                UNION ALL SELECT 2, 1, 20
            ), events AS (
                SELECT *, named_struct('ord', ord) AS details
                FROM order_events
            )";
        for sql in [
            // ONE ROW PER MATCH + outer struct field access
            format!(
                "{base_cte}
                 SELECT customer, first_details['ord'] AS d
                 FROM events MATCH_RECOGNIZE (
                     PARTITION BY customer ORDER BY ord
                     MEASURES FIRST(A.details) AS first_details
                     ONE ROW PER MATCH
                     PATTERN (A+) DEFINE A AS amount > 0
                 ) ORDER BY customer"
            ),
            // ALL ROWS PER MATCH + outer struct field access
            format!(
                "{base_cte}
                 SELECT customer, details['ord'] AS d
                 FROM events MATCH_RECOGNIZE (
                     PARTITION BY customer ORDER BY ord
                     ALL ROWS PER MATCH
                     PATTERN (A+) DEFINE A AS amount > 0
                 ) WHERE ord = 1 ORDER BY customer"
            ),
            // SubqueryAlias + outer struct field access and filter
            format!(
                "{base_cte}
                 SELECT mr.customer, mr.first_details['ord'] AS d
                 FROM (
                     SELECT * FROM events MATCH_RECOGNIZE (
                         PARTITION BY customer ORDER BY ord
                         MEASURES FIRST(A.details) AS first_details
                         ONE ROW PER MATCH
                         PATTERN (A+) DEFINE A AS amount > 0
                     )
                 ) AS mr
                 WHERE mr.customer >= 1 AND mr.first_details['ord'] = 1
                 ORDER BY mr.customer"
            ),
        ] {
            let batches = ctx.sql(&sql).await?.collect().await?;
            let pairs: Vec<(i64, i64)> = batches
                .iter()
                .flat_map(|b| {
                    let c = b
                        .column(0)
                        .as_any()
                        .downcast_ref::<Int64Array>()
                        .expect("customer int64");
                    let d = b
                        .column(1)
                        .as_any()
                        .downcast_ref::<Int64Array>()
                        .expect("detail ord int64");
                    (0..b.num_rows()).map(|i| (c.value(i), d.value(i)))
                })
                .collect();
            assert_eq!(pairs, vec![(1, 1), (2, 1)], "query failed:\n{sql}");
        }
        Ok(())
    }
}