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.

//! Safe composition of stacked `ProjectionExec` layers above a matcher input.

use datafusion::common::plan_err;
use datafusion::common::tree_node::{Transformed, TreeNode};
use datafusion::logical_expr::Operator;
use datafusion::physical_expr::expressions::{
    BinaryExpr, CaseExpr, Column, InListExpr, IsNotNullExpr, IsNullExpr, LambdaExpr,
    LambdaVariable, Literal, NotExpr,
};
use datafusion::physical_expr::projection::ProjectionExpr;
use datafusion::physical_expr_common::physical_expr::is_volatile;
use datafusion::physical_plan::projection::ProjectionExec;
use datafusion::physical_plan::{ExecutionPlan, PhysicalExpr};
use std::sync::Arc;

fn is_infallible_physical_expr(expr: &Arc<dyn PhysicalExpr>) -> bool {
    if is_volatile(expr) {
        return false;
    }
    if expr.is::<Column>() || expr.is::<Literal>() {
        return true;
    }
    if let Some(e) = expr.downcast_ref::<IsNullExpr>() {
        return is_infallible_physical_expr(e.arg());
    }
    if let Some(e) = expr.downcast_ref::<IsNotNullExpr>() {
        return is_infallible_physical_expr(e.arg());
    }
    if let Some(e) = expr.downcast_ref::<NotExpr>() {
        return is_infallible_physical_expr(e.arg());
    }
    if let Some(e) = expr.downcast_ref::<InListExpr>() {
        return is_infallible_physical_expr(e.expr())
            && e.list().iter().all(is_infallible_physical_expr);
    }
    if let Some(b) = expr.downcast_ref::<BinaryExpr>() {
        return matches!(
            b.op(),
            Operator::Eq
                | Operator::NotEq
                | Operator::Lt
                | Operator::LtEq
                | Operator::Gt
                | Operator::GtEq
                | Operator::IsDistinctFrom
                | Operator::IsNotDistinctFrom
                | Operator::And
                | Operator::Or
        ) && is_infallible_physical_expr(b.left())
            && is_infallible_physical_expr(b.right());
    }
    false
}

fn collect_column_uses(
    expr: &Arc<dyn PhysicalExpr>,
    in_short_circuit: bool,
    ref_counts: &mut [usize],
    short_circuited: &mut [bool],
) -> bool {
    // DataFusion 56 `LambdaVariable` indices depend on `input_schema.fields().len()`,
    // and inlining into lambda bodies changes fallible/volatile evaluation cardinality.
    if expr.is::<LambdaExpr>() || expr.is::<LambdaVariable>() {
        return false;
    }
    if let Some(col) = expr.downcast_ref::<Column>() {
        let idx = col.index();
        let Some(slot) = ref_counts.get_mut(idx) else {
            return false;
        };
        *slot = slot.saturating_add(1);
        if in_short_circuit {
            short_circuited[idx] = true;
        }
        return true;
    }
    if let Some(in_list) = expr.downcast_ref::<InListExpr>() {
        // DataFusion evaluates the LHS and first list item eagerly, but skips
        // later dynamic items once every row matches. Moving a projection into
        // those items could suppress its errors or volatile calls.
        return collect_column_uses(
            in_list.expr(),
            in_short_circuit,
            ref_counts,
            short_circuited,
        ) && in_list.list().iter().enumerate().all(|(index, item)| {
            collect_column_uses(
                item,
                in_short_circuit || index > 0,
                ref_counts,
                short_circuited,
            )
        });
    }
    let child_short_circuit = in_short_circuit
        || expr.is::<CaseExpr>()
        || expr
            .downcast_ref::<BinaryExpr>()
            .is_some_and(|b| matches!(b.op(), Operator::And | Operator::Or));
    for child in expr.children() {
        if !collect_column_uses(child, child_short_circuit, ref_counts, short_circuited) {
            return false;
        }
    }
    true
}

/// Compose stacked `ProjectionExec` layers (such as DataFusion's CSE split
/// projection) into one expression list over the underlying child plan without
/// duplicating volatile expressions, suppressing fallible errors, or growing
/// any expression beyond a small node cap.
pub(in crate::execution::physical) fn flatten_projections(
    projection: &ProjectionExec,
) -> (&Arc<dyn ExecutionPlan>, Vec<ProjectionExpr>) {
    const MAX_LAYERS: usize = 4;
    const MAX_COMPOSED_NODES: usize = 64;

    let mut base = projection.input();
    let mut exprs = projection.expr().to_vec();
    for _ in 0..MAX_LAYERS {
        let Some(child) = base.downcast_ref::<ProjectionExec>() else {
            break;
        };
        let child_exprs = child.expr();
        let mut ref_counts = vec![0usize; child_exprs.len()];
        let mut short_circuited = vec![false; child_exprs.len()];
        let valid_indices = exprs.iter().all(|expr| {
            collect_column_uses(&expr.expr, false, &mut ref_counts, &mut short_circuited)
        });
        if !valid_indices
            || ref_counts.iter().enumerate().any(|(i, &count)| {
                let expr = &child_exprs[i].expr;
                if is_volatile(expr) {
                    count != 1 || short_circuited[i]
                } else if !is_infallible_physical_expr(expr) {
                    count == 0 || short_circuited[i]
                } else {
                    false
                }
            })
        {
            break;
        }
        let child_node_counts: Vec<usize> = child_exprs
            .iter()
            .map(|e| {
                let mut count = 0usize;
                let _ = e.expr.apply(|_| {
                    count += 1;
                    Ok(datafusion::common::tree_node::TreeNodeRecursion::Continue)
                });
                count
            })
            .collect();
        let mut composed = Vec::with_capacity(exprs.len());
        let mut ok = true;
        for proj in &exprs {
            let mut nodes = 0usize;
            let rewritten = Arc::clone(&proj.expr).transform_up(|node| {
                if let Some(col) = node.downcast_ref::<Column>() {
                    let idx = col.index();
                    nodes += child_node_counts[idx];
                    if nodes > MAX_COMPOSED_NODES {
                        return plan_err!("composed projection exceeds node budget");
                    }
                    Ok(Transformed::yes(Arc::clone(&child_exprs[idx].expr)))
                } else {
                    nodes += 1;
                    if nodes > MAX_COMPOSED_NODES {
                        return plan_err!("composed projection exceeds node budget");
                    }
                    Ok(Transformed::no(node))
                }
            });
            match rewritten {
                Ok(t) => composed.push(ProjectionExpr::new(t.data, proj.alias.clone())),
                Err(_) => {
                    ok = false;
                    break;
                }
            }
        }
        if !ok {
            break;
        }
        exprs = composed;
        base = child.input();
    }
    (base, exprs)
}