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.

//! Physical evaluator, VM-artifact, and residual-state tests.

use super::tests::{
    TestPlanSpec, assemble_test_exec, prepare_test_plan, test_input_schema,
};
use super::*;
use crate::core::vm::{AggregateLayout, RegisterLayout, VmTier};
use crate::core::{NavigationOffset, Pattern, Symbol, SymbolEvalMode, SymbolId};
use crate::execution::matching::predicate_test_helper;
use crate::execution::matching::program::contracts::{
    ExecutableMatchProgramInput, ExecutableSymbolProgramInput, SymbolProgramTable,
    UserSymbolProgram,
};
use crate::execution::matching::test_symbol_columns;
use crate::execution::matching::{ExecutableMatchProgram, add_count_accumulator};
use datafusion::arrow::array::{BooleanArray, Int32Array};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::common::Result;
use datafusion::datasource::{memory::MemorySourceConfig, source::DataSourceExec};
use datafusion::physical_expr::{PhysicalExpr, expressions::Literal};
use datafusion::physical_plan::{ExecutionPlan, empty::EmptyExec};
use datafusion::scalar::ScalarValue;
use futures::TryStreamExt;
use std::sync::Arc;

#[tokio::test]
async fn match_aware_runtime_registers_and_records_stateful_metrics() -> Result<()> {
    let schema = test_input_schema();
    let batch = RecordBatch::try_new(
        Arc::clone(&schema),
        vec![
            Arc::new(Int32Array::from(vec![1, 2])),
            Arc::new(BooleanArray::from(vec![true, true])),
        ],
    )?;
    let source = MemorySourceConfig::try_new(&[vec![batch]], schema, None)?;
    let exec = build_match_aware_test_exec(
        TestPlanSpec::new(DataSourceExec::from_data_source(source)),
        match_number_symbol_programs(),
        false,
        Vec::new(),
    )?;
    let batches: Vec<RecordBatch> = exec
        .execute(0, Arc::new(datafusion::execution::TaskContext::default()))?
        .try_collect()
        .await?;
    assert_eq!(batches.iter().map(RecordBatch::num_rows).sum::<usize>(), 2);
    let metrics = exec.metrics().unwrap();
    assert!(metrics.iter().any(|metric| {
        metric.value().name() == "route.evaluator.direct_expr"
            && metric.value().as_usize() > 0
    }));
    assert!(
        metrics
            .iter()
            .any(|metric| metric.value().name() == "deferred_requests")
    );
    assert!(
        metrics
            .iter()
            .any(|metric| { metric.value().name() == "route.evaluator.static" })
    );
    Ok(())
}

fn hybrid_symbol_programs() -> SymbolProgramTable {
    let predicate =
        Arc::new(Literal::new(ScalarValue::Boolean(Some(true)))) as Arc<dyn PhysicalExpr>;
    SymbolProgramTable::try_new(vec![UserSymbolProgram::try_new(
        SymbolId::try_new(1,2).unwrap(),SymbolEvalMode::Hybrid,Some(predicate),
        Some(crate::execution::matching::program::contracts::PhysicalHybridGuardExpr::Unknown),
        vec![],None).unwrap()],Default::default()).unwrap()
}

fn empty_symbol_programs(aggregate_count: usize) -> SymbolProgramTable {
    SymbolProgramTable::try_new(
        vec![
            UserSymbolProgram::try_new(
                SymbolId::try_new(1, 2).unwrap(),
                SymbolEvalMode::Static,
                None,
                None,
                Vec::new(),
                None,
            )
            .unwrap(),
        ],
        RegisterLayout::builder(0, vec![AggregateLayout::default(); aggregate_count])
            .vm_tier(VmTier::Standard)
            .try_build()
            .unwrap(),
    )
    .expect("default test symbol program should be valid")
}

fn match_number_symbol_programs() -> SymbolProgramTable {
    let local_predicate =
        Arc::new(Literal::new(ScalarValue::Boolean(Some(true)))) as Arc<dyn PhysicalExpr>;
    let predicate = predicate_test_helper::positive_match_number();
    SymbolProgramTable::try_new(
        vec![
            UserSymbolProgram::try_new(
                SymbolId::try_new(1, 2).unwrap(),
                SymbolEvalMode::Incremental,
                Some(local_predicate),
                None,
                Vec::new(),
                Some(predicate),
            )
            .unwrap(),
        ],
        Default::default(),
    )
    .expect("MATCH_NUMBER test symbol program should be valid")
}

fn build_match_aware_test_exec(
    spec: TestPlanSpec,
    symbol_programs: SymbolProgramTable,
    has_lookahead_defines: bool,
    aggregate_programs: Vec<
        crate::execution::matching::program::contracts::AggregateProgram,
    >,
) -> Result<MatchRecognizePatternExec> {
    let prepared = prepare_test_plan(spec)?;
    let input_schema = prepared.spec.input.schema();
    let local = symbol_programs.test_local_predicate_ids();
    let aware = symbol_programs.deferred_symbol_ids().collect::<Vec<_>>();
    let columns = test_symbol_columns(
        &prepared.pattern.compiled_automaton,
        &aware,
        &input_schema,
        &local,
    )?;
    let mut program = ExecutableMatchProgram::try_new(ExecutableMatchProgramInput {
        input_schema,
        normalized_pattern: prepared.pattern.normalized_pattern.clone(),
        max_define_lookahead_rows: if has_lookahead_defines {
            NavigationOffset::ONE
        } else {
            NavigationOffset::ZERO
        },
        has_deferred_history_operations: has_lookahead_defines,
        symbols: ExecutableSymbolProgramInput {
            automaton: Arc::clone(&prepared.pattern.compiled_automaton),
            relationships: Default::default(),
            symbol_columns: columns,
            static_extractions: Vec::new(),
            vm_static_inputs: Default::default(),
            symbol_programs,
        },
        aggregate_programs,
        output: Arc::clone(&prepared.output),
        after_match_skip: prepared.spec.after_match_skip.clone(),
        deferred_evaluator_factory: None,
    })?;
    // These fixtures supply infallible predicates. Mirror the logical planner's
    // proof rather than the conservative programmatic constructor default.
    program.can_skip_candidate_evaluation = true;
    let display = MatchPlanDisplay::new(
        prepared.pattern.display_pattern.clone(),
        prepared.symbols.clone(),
        vec![SymbolEvalMode::Static.to_string()],
        &program,
    );
    assemble_test_exec(prepared, program, display)
}

#[test]
fn optional_define_state_retains_its_stream_and_halo_policy() -> Result<()> {
    for (name, lookahead, symbols, managed, expected_retention, expected_max) in [
        (
            "lookahead",
            true,
            empty_symbol_programs(0),
            false,
            PartitionRetention::LogicalPartitionBoundaryOnly,
            Some(1),
        ),
        (
            "managed bounded state",
            false,
            empty_symbol_programs(1),
            true,
            PartitionRetention::ThresholdSafe,
            Some(2),
        ),
        (
            "hybrid predicate",
            false,
            hybrid_symbol_programs(),
            false,
            PartitionRetention::ThresholdSafe,
            None,
        ),
        (
            "global match number",
            false,
            match_number_symbol_programs(),
            false,
            PartitionRetention::ThresholdSafe,
            None,
        ),
    ] {
        let mut schema = test_input_schema();
        let aggregates = if managed {
            let (batch, aggregate, _) = add_count_accumulator(
                RecordBatch::new_empty(schema),
                SymbolId::try_new(1, 2).unwrap(),
            );
            schema = batch.schema();
            vec![aggregate]
        } else {
            vec![]
        };
        let mut spec = TestPlanSpec::new(Arc::new(EmptyExec::new(schema)));
        if managed {
            let a = || Pattern::Symbol(Symbol::Named("A".into()));
            spec.pattern =
                Pattern::Alternation(vec![a(), Pattern::Concat(vec![a(), a()])]);
            spec.after_match_skip = ResolvedAfterMatchSkip::ToNextRow;
        }
        let exec = build_match_aware_test_exec(spec, symbols, lookahead, aggregates)?;
        assert_eq!(
            (
                exec.policy().retention(),
                exec.policy()
                    .parallel_qualification()
                    .map(|p| p.max_match_len())
            ),
            (expected_retention, expected_max),
            "{name}"
        );
    }
    Ok(())
}

#[test]
fn physical_fallback_match_number_rejects_halo_qualification() -> Result<()> {
    use crate::core::MatchMetadataColumn;
    use datafusion::arrow::datatypes::{DataType, Field, Schema};
    use datafusion::logical_expr::Operator;
    use datafusion::physical_expr::expressions::{BinaryExpr, CastExpr};

    let match_num_name = MatchMetadataColumn::MatchNumber.as_ref();
    let schema = Arc::new(Schema::new(vec![
        Field::new("x", DataType::Int32, true),
        Field::new("__mr_symbol_a", DataType::Boolean, false),
        Field::new(match_num_name, DataType::Int64, true),
    ]));
    let cast_match_number: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
        Arc::new(CastExpr::new(
            Arc::new(Column::new(match_num_name, 2)),
            DataType::Utf8,
            None,
        )),
        Operator::Eq,
        Arc::new(Literal::new(ScalarValue::Utf8(Some("1".into())))),
    ));
    let bitwise_match_number: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
        Arc::new(BinaryExpr::new(
            Arc::new(Column::new(match_num_name, 2)),
            Operator::BitwiseAnd,
            Arc::new(Literal::new(ScalarValue::Int64(Some(1)))),
        )),
        Operator::Eq,
        Arc::new(Literal::new(ScalarValue::Int64(Some(1)))),
    ));
    let row_only: Arc<dyn PhysicalExpr> = Arc::new(BinaryExpr::new(
        Arc::new(Column::new("x", 0)),
        Operator::Gt,
        Arc::new(Literal::new(ScalarValue::Int32(Some(0)))),
    ));

    for (label, local_predicate, expected_global_match_number) in [
        ("cast match_number", cast_match_number, true),
        ("bitwise match_number", bitwise_match_number, true),
        ("row-only physical predicate", row_only, false),
    ] {
        let symbols = SymbolProgramTable::try_new(
            vec![UserSymbolProgram::try_new(
                SymbolId::try_new(1, 2).unwrap(),
                SymbolEvalMode::Incremental,
                Some(local_predicate),
                None,
                Vec::new(),
                None,
            )?],
            Default::default(),
        )?;
        let exec = build_match_aware_test_exec(
            TestPlanSpec::new(Arc::new(EmptyExec::new(Arc::clone(&schema)))),
            symbols,
            false,
            Vec::new(),
        )?;
        let program = exec.program().as_ref();
        assert_eq!(
            program.has_global_match_number_predicate(),
            expected_global_match_number,
            "{label}"
        );
        assert_eq!(
            program.stream_requirements().independent_candidate_starts,
            !expected_global_match_number,
            "{label}"
        );
        assert_eq!(
            exec.policy()
                .parallel_qualification()
                .map(|p| p.max_match_len()),
            (!expected_global_match_number).then_some(1),
            "{label}"
        );
    }
    Ok(())
}

#[test]
fn optional_expression_traversal_visits_the_actual_predicate_arc() -> Result<()> {
    let predicate: Arc<dyn PhysicalExpr> =
        Arc::new(Literal::new(ScalarValue::Boolean(Some(true))));
    let symbols = SymbolProgramTable::try_new(
        vec![UserSymbolProgram::try_new(
            SymbolId::try_new(1, 2).unwrap(),
            SymbolEvalMode::Incremental,
            Some(Arc::clone(&predicate)),
            None,
            vec![],
            None,
        )?],
        Default::default(),
    )?;
    let input: Arc<dyn ExecutionPlan> = Arc::new(EmptyExec::new(test_input_schema()));
    let exec =
        build_match_aware_test_exec(TestPlanSpec::new(input), symbols, false, vec![])?;
    let mut roots = Vec::new();
    let recursion = exec.apply_expressions(&mut |root| {
        roots.push(Arc::clone(root));
        Ok(TreeNodeRecursion::Continue)
    })?;
    assert_eq!(recursion, TreeNodeRecursion::Continue);
    assert_eq!(roots.len(), 1);
    assert!(Arc::ptr_eq(&roots[0], &predicate));
    Ok(())
}

#[test]
fn replace_children_preserves_optional_program_and_define_bindings() -> Result<()> {
    let schema = test_input_schema();
    let input = Arc::new(EmptyExec::new(Arc::clone(&schema))) as Arc<dyn ExecutionPlan>;
    let exec = Arc::new(build_match_aware_test_exec(
        TestPlanSpec::new(Arc::clone(&input)),
        match_number_symbol_programs(),
        false,
        Vec::new(),
    )?);
    let replacement = Arc::new(EmptyExec::new(schema)) as Arc<dyn ExecutionPlan>;
    let rebuilt = Arc::clone(&exec).replace_children(
        vec![Arc::clone(&replacement)],
        ReplaceChildrenOptions::new(ChildrenPropertiesMode::Recompute),
    )?;
    let rebuilt = rebuilt.downcast_ref::<MatchRecognizePatternExec>().unwrap();
    assert!(Arc::ptr_eq(exec.program(), rebuilt.program()));
    assert!(Arc::ptr_eq(rebuilt.children()[0], &replacement));
    assert!(rebuilt.policy().parallel_qualification().is_none());
    Ok(())
}