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.

//! Match-aware DEFINE round trips.

use super::*;

const CTE_QUALIFIED_COLUMNS: [(&str, DataType, bool); 4] = [
    ("company", DataType::Utf8, true),
    ("last_price", DataType::Int64, true),
    ("row_count", DataType::Int64, false),
    ("last_rank", DataType::UInt64, true),
];

async fn cte_qualified_source_case() -> Result<(SessionContext, LogicalPlan)> {
    let ctx = context_with_input().await?;
    let sql = r#"
WITH input AS (
  SELECT *, ROW_NUMBER() OVER (ORDER BY ts) AS source_rank FROM t
)
SELECT company, last_price, row_count, last_rank
FROM input
MATCH_RECOGNIZE (
  PARTITION BY company
  ORDER BY ts
  MEASURES
MAX(A.price) AS last_price, COUNT(*) AS row_count, MAX(A.source_rank) AS last_rank
  ONE ROW PER MATCH
  AFTER MATCH SKIP PAST LAST ROW
  PATTERN (A+)
  DEFINE
A AS (NEXT(ts) IS NULL OR NEXT(ts) >= ts) AND MAX(A.price) >= 0
)
ORDER BY company, last_price
"#;
    let direct = sql_plan(&ctx, sql).await?;
    Ok((ctx, direct))
}

#[tokio::test]
async fn cte_qualified_source_columns_roundtrip_execution() -> Result<()> {
    let (ctx, direct) = cte_qualified_source_case().await?;
    for optimize in [false, true] {
        let plan = if optimize {
            ctx.state().optimize(&direct)?
        } else {
            direct.clone()
        };
        assert_roundtrip_output(
            &ctx,
            plan,
            &CTE_QUALIFIED_COLUMNS,
            &[vec![
                "acme".into(),
                14_i64.into(),
                3_i64.into(),
                3_u64.into(),
            ]],
        )
        .await?;
    }
    Ok(())
}

#[tokio::test]
async fn cte_qualified_source_rejects_changed_prepared_navigation() -> Result<()> {
    let (ctx, direct) = cte_qualified_source_case().await?;
    let node = match_recognize_node(&direct).expect("native match node");
    let changed = rewrite_match_input(direct.clone(), |input| {
        Ok(input
            .clone()
            .transform_up(|plan| {
                let LogicalPlan::Window(window) = &plan else {
                    return Ok(Transformed::no(plan));
                };
                let mut expressions = window.window_expr.clone();
                for expression in &mut expressions {
                    let Expr::Alias(alias) = expression else {
                        continue;
                    };
                    let Some(expected) = node.prepared_expr(&alias.name) else {
                        continue;
                    };
                    assert_eq!(expected, alias.expr.as_ref());
                    let Expr::WindowFunction(window) = alias.expr.as_mut() else {
                        panic!("prepared alias must contain a window");
                    };
                    window.params.args[0] = window.params.args[0].clone() - lit(100_i64);
                }
                Ok(Transformed::yes(LogicalPlan::Window(
                    datafusion::logical_expr::Window::try_new_with_schema(
                        expressions,
                        Arc::clone(&window.input),
                        Arc::clone(&window.schema),
                    )?,
                )))
            })?
            .data)
    })?;

    // The changed NEXT argument must affect execution before export rejects it.
    assert_output(
        &ctx,
        changed.clone(),
        &CTE_QUALIFIED_COLUMNS,
        &[vec![
            "acme".into(),
            14_i64.into(),
            1_i64.into(),
            3_u64.into(),
        ]],
    )
    .await?;
    assert_export_rejected(&ctx, &changed, "prepared");
    Ok(())
}

#[tokio::test]
async fn cte_qualified_source_rejects_optimized_changed_comparison() -> Result<()> {
    let (ctx, direct) = cte_qualified_source_case().await?;
    let changed_comparison =
        rewrite_prepared_projection(direct, "__mr_static_predicate_and_0", |expr| {
            Ok(expr
                .transform_up(|expr| {
                    let Expr::BinaryExpr(mut binary) = expr else {
                        return Ok(Transformed::no(expr));
                    };
                    if matches!(binary.left.as_ref(), Expr::Column(_))
                        && matches!(binary.right.as_ref(), Expr::Column(_))
                        && let Some(op) = binary.op.negate()
                    {
                        binary.op = op;
                        return Ok(Transformed::yes(Expr::BinaryExpr(binary)));
                    }
                    Ok(Transformed::no(Expr::BinaryExpr(binary)))
                })?
                .data)
        })?;
    let changed = ctx.state().optimize(&changed_comparison)?;
    // The comparison control also covers optimizer propagation of preparation.
    assert_output(
        &ctx,
        changed.clone(),
        &CTE_QUALIFIED_COLUMNS,
        &[vec![
            "acme".into(),
            14_i64.into(),
            1_i64.into(),
            3_u64.into(),
        ]],
    )
    .await?;
    assert_export_rejected(&ctx, &changed, "prepared");
    Ok(())
}

#[tokio::test]
async fn cte_qualified_source_rejects_renamed_prepared_window() -> Result<()> {
    let (ctx, direct) = cte_qualified_source_case().await?;
    let node = match_recognize_node(&direct).expect("native match node");
    let window = node
        .input()
        .schema()
        .fields()
        .iter()
        .find_map(|field| {
            node.prepared_expr(field.name())
                .filter(|expr| matches!(expr, Expr::WindowFunction(_)))
        })
        .expect("prepared navigation window");
    let renamed = rewrite_match_input(direct.clone(), |input| {
        LogicalPlanBuilder::from(input.clone())
            .window(vec![window.clone().alias("renamed_preparation")])?
            .build()
    })?;
    assert_export_rejected(&ctx, &renamed, "prepared window 'renamed_preparation'");
    Ok(())
}

#[tokio::test]
async fn cte_qualified_source_rejects_unaliased_window_above_preparation() -> Result<()> {
    use datafusion::common::DataFusionError;
    use datafusion::functions_window::lead_lag::lag_udwf;

    let (_, direct) = cte_qualified_source_case().await?;
    let window = lag_udwf().call(vec![lit(42_i64), lit(1_u64), lit(0_i64)]);
    let (_, name) = window.qualified_name();
    let changed = rewrite_match_input(direct, |input| {
        LogicalPlanBuilder::from(input.clone())
            .window(vec![window.clone()])?
            .build()
    })?;
    let node = match_recognize_node(&changed).expect("native match node");
    let error = export_input(node).unwrap_err();
    assert!(
        matches!(error, DataFusionError::Plan(ref reason) if reason.contains(&format!("prepared window '{name}'"))),
        "{error}"
    );
    Ok(())
}

#[tokio::test]
async fn lifted_sum_inputs_preserve_their_expression() -> Result<()> {
    let ctx = export_context().await?;
    let direct = sql_plan(
        &ctx,
        "WITH input AS (SELECT k, ts, CAST(price AS DOUBLE) AS price FROM export_input)
        SELECT k, n FROM input AS export_input MATCH_RECOGNIZE (
        PARTITION BY k ORDER BY ts MEASURES COUNT(*) AS n
        PATTERN (A+) DEFINE A AS SUM(A.price * 2.0) < 70) ORDER BY k, n",
    )
    .await?;
    // Integer multiplication remains candidate-local because it can overflow.
    // Use a total Float64 expression and require actual preparation before
    // testing that mutations of that prepared value cannot be exported.
    let prepared = match_recognize_node(&direct)
        .expect("matcher")
        .prepared_expr("__mr_expr_0")
        .expect("safe Float64 multiplication must be prepared")
        .clone();

    let columns = [("k", DataType::Int64, true), ("n", DataType::Int64, false)];
    assert_roundtrip_output(
        &ctx,
        direct.clone(),
        &columns,
        &[
            vec![1_i64.into(), 1_i64.into()],
            vec![1_i64.into(), 2_i64.into()],
            vec![2_i64.into(), 3_i64.into()],
        ],
    )
    .await?;
    let projected = rewrite_match_input(direct.clone(), |input| {
        project_input_column(input, "__mr_expr_0", lit(1.0_f64))
    })?;
    let windowed = rewrite_match_input(direct, |input| {
        replace_column_with_lag(input, "__mr_expr_0", prepared.clone(), lit(0.0_f64))
    })?;

    for (changed, optimize) in [(projected, false), (windowed, true)] {
        let plan = if optimize {
            ctx.state().optimize(&changed)?
        } else {
            changed
        };
        assert_output(
            &ctx,
            plan.clone(),
            &columns,
            &[
                vec![1_i64.into(), 3_i64.into()],
                vec![2_i64.into(), 3_i64.into()],
            ],
        )
        .await?;
        assert_export_rejected(&ctx, &plan, "prepared");
    }
    Ok(())
}

#[tokio::test]
async fn compound_prev_null_defaults_roundtrip() -> Result<()> {
    let ctx = context_with_input().await?;
    for (integer, rows) in [
        (9_007_199_254_740_993_i64, vec![vec![2_i64.into()]]),
        (9_007_199_254_740_992_i64, vec![]),
    ] {
        let plan = sql_plan(
            &ctx,
            &format!(
                "WITH src(id,v) AS (VALUES (1,9007199254740993),(2,20),(3,30))
             SELECT n FROM src MATCH_RECOGNIZE (
                ORDER BY id MEASURES COUNT(*) AS n ONE ROW PER MATCH PATTERN (A B)
                DEFINE A AS id=2, B AS PREV(CAST(A.v AS DOUBLE))=9007199254740992.0
                    AND PREV(A.v)={integer})"
            ),
        )
        .await?;
        assert_roundtrip_output(&ctx, plan, &[("n", DataType::Int64, false)], &rows)
            .await?;
    }
    Ok(())
}

#[tokio::test]
async fn prepared_prev_date64_defaults_roundtrip() -> Result<()> {
    let ctx = context_with_input().await?;
    for default in [Some(-86_400_001_i64), Some(0), Some(86_400_001), None] {
        let millis = default.map_or_else(|| "NULL".into(), |value| value.to_string());
        let predicate =
            default.map_or_else(|| "IS NULL".into(), |value| format!("= {value}"));
        let date = format!("arrow_cast(CAST({millis} AS BIGINT), 'Date64')");
        let plan = sql_plan(
            &ctx,
            &format!(
                "WITH raw(ord, phase, millis) AS (VALUES (1,0,86400000),(2,1,172800000)),
                src AS (SELECT ord, phase, arrow_cast(CAST(millis AS BIGINT), 'Date64') AS value FROM raw)
                SELECT CAST(previous AS BIGINT) AS previous_ms FROM src MATCH_RECOGNIZE (
                    ORDER BY ord MEASURES PREV(A.value, 1, {date}) AS previous
                    ONE ROW PER MATCH PATTERN (A B)
                    DEFINE A AS phase = 0,
                        B AS phase = 1 AND CAST(PREV(A.value, 1, {date}) AS BIGINT) {predicate})"
            ),
        )
        .await?;
        assert_roundtrip_output(
            &ctx,
            plan,
            &[("previous_ms", DataType::Int64, true)],
            &[vec![datafusion::common::ScalarValue::Int64(default)]],
        )
        .await?;
    }
    Ok(())
}

#[tokio::test]
async fn mixed_integer_static_extraction_survives_literal_narrowing() -> Result<()> {
    use datafusion::arrow::array::Int32Array;
    let ctx = context_with_input().await?;
    ctx.register_batch(
        "source_values",
        RecordBatch::try_from_iter([
            (
                "ord",
                Arc::new(Int32Array::from(vec![1, 2, 3, 4, 5])) as ArrayRef,
            ),
            (
                "value",
                Arc::new(Int32Array::from(vec![1, 2, 0, -1, 4])) as ArrayRef,
            ),
        ])?,
    )?;
    let direct = sql_plan(
        &ctx,
        "SELECT n FROM source_values MATCH_RECOGNIZE (
        ORDER BY ord MEASURES COUNT(A.*) AS n ONE ROW PER MATCH
        PATTERN (A+) DEFINE A AS value <> 0 AND COUNT(A.*) <= 2)",
    )
    .await?;

    // Five rows contain one rejected zero. Dropping the static guard would
    // produce an extra singleton instead of these two pairs.
    for optimize in [false, true] {
        let plan = if optimize {
            ctx.state().optimize(&direct)?
        } else {
            direct.clone()
        };
        assert_roundtrip_output(
            &ctx,
            plan,
            &[("n", DataType::Int64, false)],
            &[vec![2_i64.into()], vec![2_i64.into()]],
        )
        .await?;
    }
    Ok(())
}