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.

//! Wire declaration and executable admission share semantic requirements.

use super::*;
use datafusion::logical_expr::{Volatility, create_udf};

fn candidate_payload() -> payload::MatchRecognizeRel {
    let mut payload = base_payload();
    payload.definitions[1].predicate = Some(payload::SourceExpression {
        kind: Some(payload::source_expression::Kind::Binary(
            payload::BinaryExpr {
                left: Some(Box::new(pattern_field("B", 2))),
                op: payload::BinaryOperator::Gt as i32,
                right: Some(Box::new(pattern_field("A", 2))),
            },
        )),
    });
    payload
}

fn candidate_payload_with_marker() -> payload::MatchRecognizeRel {
    let mut payload = candidate_payload();
    payload
        .required_features
        .push(MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE.into());
    payload
}

#[tokio::test]
async fn inspection_decodes_the_match_aware_marker_and_definitions() -> Result<()> {
    let ctx = context_with_input().await?;
    let payload = candidate_payload_with_marker();
    let state = ctx.state();
    let extensions = Extensions::default();
    let consumer = MatchRecognizeSubstraitConsumer::new(&extensions, &state);
    let decoded =
        decode_match_recognize_detail(&consumer, &encode_detail(payload), &test_schema())
            .await?;
    assert!(decoded.declares_match_aware_defines);
    assert_eq!(decoded.spec.definitions.len(), 2);

    Ok(())
}

#[tokio::test]
async fn every_executable_boundary_requires_truthful_define_declaration() -> Result<()> {
    let ctx = context_with_input().await?;
    for boundary in [
        MatchRecognizeBoundary::CompletePlan,
        MatchRecognizeBoundary::RowStreamNode,
        MatchRecognizeBoundary::OneRowNode,
    ] {
        let mut payload = candidate_payload();
        if boundary != MatchRecognizeBoundary::CompletePlan {
            payload.semantic_node = true;
            payload
                .required_features
                .push(DATAFUSION_WINDOW_MODIFIERS_FEATURE.into());
        }
        if boundary == MatchRecognizeBoundary::OneRowNode {
            payload.semantic_node_finalizes_one_row = true;
            payload
                .required_features
                .push(DATAFUSION_SEMANTIC_ONE_ROW_FEATURE.into());
        }
        let error = from_substrait_plan_with_match_recognize(
            &ctx.state(),
            &plan_for_payload(payload),
        )
        .await
        .unwrap_err();
        assert!(
            error.to_string().contains(
                "missing required feature match_recognize.match_aware_defines_v1"
            ),
            "{boundary:?}: {error}"
        );
    }

    // Both semantic output variants share this guard; one raw row-stream
    // payload isolates it without constructing another complete SQL plan.
    let mut missing_positions = base_payload();
    missing_positions.semantic_node = true;
    missing_positions
        .required_features
        .retain(|feature| feature != MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE);
    missing_positions
        .required_features
        .push(DATAFUSION_WINDOW_MODIFIERS_FEATURE.into());
    let state = ctx.state();
    let extensions = Extensions::default();
    let consumer = MatchRecognizeSubstraitConsumer::new(&extensions, &state);
    let error = decode_match_recognize_detail(
        &consumer,
        &encode_detail(missing_positions),
        &test_schema(),
    )
    .await
    .unwrap_err();
    assert!(
        error
            .to_string()
            .contains(MATCH_RECOGNIZE_POSITIONAL_FIELD_REFS_FEATURE),
        "{error}"
    );
    Ok(())
}

#[tokio::test]
async fn output_aggregates_and_navigation_do_not_declare_match_aware_defines()
-> Result<()> {
    let ctx = context_with_input().await?;
    let source = ctx.sql("SELECT n, first_price FROM t MATCH_RECOGNIZE (ORDER BY ts MEASURES COUNT(A.*) AS n, FIRST(A.price) AS first_price PATTERN (A+) DEFINE A AS price > 0)").await?.logical_plan().clone();
    let exported = to_substrait_plan_with_match_recognize(&source, &ctx.state())?;
    let payload = root_payload(&exported)?;
    assert!(
        !payload
            .required_features
            .iter()
            .any(|feature| feature == MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE)
    );

    roundtrip::assert_roundtrip_output(
        &ctx,
        source,
        &[
            ("n", DataType::Int64, false),
            ("first_price", DataType::Int64, true),
        ],
        &[vec![3_i64.into(), 10_i64.into()]],
    )
    .await?;
    Ok(())
}

#[tokio::test]
async fn normalized_static_and_custom_function_defines_roundtrip_without_marker()
-> Result<()> {
    let ctx = context_with_input().await?;
    ctx.register_udf(create_udf(
        "source_identity",
        vec![DataType::Int64],
        DataType::Int64,
        Volatility::Immutable,
        Arc::new(|args| Ok(args[0].clone())),
    ));
    for predicate in ["LAST(A.price, 0) > 0", "source_identity(price) > 0"] {
        let source = ctx
            .sql(&format!(
                "SELECT n FROM t MATCH_RECOGNIZE (ORDER BY ts \
                 MEASURES COUNT(*) AS n PATTERN (A+) DEFINE A AS {predicate})"
            ))
            .await?
            .logical_plan()
            .clone();
        let exported = to_substrait_plan_with_match_recognize(&source, &ctx.state())?;
        assert!(
            !root_payload(&exported)?
                .required_features
                .iter()
                .any(|feature| feature == MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE),
            "{predicate}"
        );
        roundtrip::assert_roundtrip_output(
            &ctx,
            source,
            &[("n", DataType::Int64, false)],
            &[vec![3_i64.into()]],
        )
        .await?;
    }
    let count_source = ctx
        .sql(
            "SELECT n FROM t MATCH_RECOGNIZE (ORDER BY ts \
             MEASURES COUNT(*) AS n PATTERN (A+) DEFINE A AS COUNT(A.*) > 0)",
        )
        .await?
        .logical_plan()
        .clone();
    let exported = to_substrait_plan_with_match_recognize(&count_source, &ctx.state())?;
    assert!(
        root_payload(&exported)?
            .required_features
            .iter()
            .any(|feature| feature == MATCH_RECOGNIZE_MATCH_AWARE_DEFINES_FEATURE)
    );
    roundtrip::assert_roundtrip_output(
        &ctx,
        count_source,
        &[("n", DataType::Int64, false)],
        &[vec![3_i64.into()]],
    )
    .await?;
    Ok(())
}

mod stateful;