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.

use super::*;
use crate::core::RepetitionQuantifier;
use crate::execution::matching::path::Sym;

fn sym(name: &str) -> Pattern {
    Pattern::Symbol(Symbol::Named(name.into()))
}

struct OrderedHarness {
    matcher: crate::execution::matching::PatternMatcher,
    input: BatchCollection,
    provider: MultiBatchBoolColumns,
}
impl OrderedHarness {
    fn new(pattern: Pattern, columns: &[(&str, &[bool])]) -> Self {
        Self::with_compact_paths(pattern, columns, false)
    }
    fn with_compact_paths(
        pattern: Pattern,
        columns: &[(&str, &[bool])],
        compact: bool,
    ) -> Self {
        let pattern = NormalizedPattern::Ast(pattern);
        let names = columns
            .iter()
            .map(|(name, _)| name.to_string())
            .collect::<Vec<_>>();
        let compiled = Arc::new(CompiledAutomaton::compile(&pattern, &names).unwrap());
        let arrays = columns
            .iter()
            .map(|(_, values)| BooleanArray::from(values.to_vec()))
            .collect::<Vec<_>>();
        let schema = Arc::new(Schema::new(
            columns
                .iter()
                .map(|(name, _)| {
                    Field::new(
                        format!("__mr_symbol_{}", name.to_lowercase()),
                        DataType::Boolean,
                        false,
                    )
                })
                .collect::<Vec<_>>(),
        ));
        let batch = RecordBatch::try_new(
            Arc::clone(&schema),
            arrays
                .iter()
                .map(|array| Arc::new(array.clone()) as ArrayRef)
                .collect(),
        )
        .unwrap();
        let rows = batch.num_rows();
        let input = BatchCollection::try_new(vec![batch], Arc::clone(&schema)).unwrap();
        let mut config = MatchRecognizeConfig::default();
        config.diagnostics.disable_compact_paths = !compact;
        let programs = compact.then(|| {
            test_symbol_programs_with_vm_for_automaton(
                &compiled,
                &[],
                &[],
                vec![vec![]; names.len()],
                RegisterLayout::empty_compact(0),
            )
        });
        let mut matcher =
            build_test_matcher(schema, pattern, compiled, &config, |input| {
                if let Some(programs) = programs {
                    input.symbols.symbol_programs = programs;
                }
            })
            .unwrap();
        matcher.force_generic_scan_for_test(!compact);
        let provider = MultiBatchBoolColumns::with_offsets(
            std::iter::once(vec![BooleanArray::from(vec![false; rows])])
                .chain(arrays.into_iter().map(|array| vec![array]))
                .collect(),
            vec![],
            vec![],
            vec![rows],
            vec![0],
        );
        Self {
            matcher,
            input,
            provider,
        }
    }
    fn drive(
        &self,
        ctx: &mut ScanContext,
        start: bool,
        rows: usize,
        eof: bool,
        yielding: bool,
    ) {
        let mut first = start;
        for _ in 0..10000 {
            let mut session =
                test_session(&self.matcher, &self.provider, &self.input, ctx);
            session.range.total_rows = rows + usize::from(eof);
            session.range.read_end_row = rows;
            session.range.has_virtual_row = eof;
            session.yield_policy = if yielding {
                YieldPolicy::from_test_budget(1)
            } else {
                YieldPolicy::Disabled
            };
            let step = if first {
                self.matcher.start_candidate_scan(session)
            } else {
                self.matcher.resume_candidate_scan(session)
            }
            .unwrap();
            first = false;
            if step == ComputeStep::Complete {
                return;
            }
        }
        panic!("ordered scan did not finish");
    }
    fn labels(&self, ctx: &ScanContext) -> Vec<Sym> {
        let mut node = Some(ctx.scan_state.incumbent.unwrap().best_match.path_end);
        let mut labels = Vec::new();
        while let Some(index) = node {
            let entry = &ctx.thread_store.node_arena[index as usize];
            labels.push(entry.step.sym);
            node = entry.prev;
        }
        labels.reverse();
        labels
    }
}

#[test]
fn ordered_threads_keep_preferred_continuations_ahead_of_the_incumbent() {
    // Both alternatives consume row zero; C accepts first in time, but A B
    // remains ahead of it. On the next row it either wins or leaves C intact.
    for b_matches in [false, true] {
        let h = OrderedHarness::new(
            Pattern::Alternation(vec![
                Pattern::Concat(vec![sym("A"), sym("B")]),
                sym("C"),
            ]),
            &[
                ("A", &[true, false]),
                ("B", &[false, b_matches]),
                ("C", &[true, true]),
            ],
        );
        for yielding in [false, true] {
            let mut ctx = initialized_scan_context(&h.matcher);
            h.drive(&mut ctx, true, 1, false, yielding);
            assert_eq!(h.labels(&ctx), [Sym::from_index(3)]);
            assert_eq!(ctx.thread_store.buffers.as_ref().unwrap().active.len(), 1);
            h.drive(&mut ctx, false, 2, true, yielding);
            assert_eq!(
                h.labels(&ctx),
                if b_matches {
                    vec![Sym::from_index(1), Sym::from_index(2)]
                } else {
                    vec![Sym::from_index(3)]
                }
            );
        }
    }
}

#[test]
fn empty_alternative_cuts_off_later_edges_but_keeps_preferred_prefixes() {
    for b_matches in [false, true] {
        let h = OrderedHarness::new(
            Pattern::Alternation(vec![
                Pattern::Concat(vec![sym("A"), sym("B")]),
                Pattern::Concat(vec![]),
                sym("C"),
            ]),
            &[
                ("A", &[true, false]),
                ("B", &[false, b_matches]),
                ("C", &[true, true]),
            ],
        );
        let mut ctx = initialized_scan_context(&h.matcher);
        h.drive(&mut ctx, true, 1, false, true);
        assert_eq!(h.labels(&ctx), [Sym::Empty]);
        assert_eq!(ctx.thread_store.buffers.as_ref().unwrap().active.len(), 1);
        h.drive(&mut ctx, false, 2, true, true);
        assert_eq!(
            h.labels(&ctx),
            if b_matches {
                vec![Sym::from_index(1), Sym::from_index(2)]
            } else {
                vec![Sym::Empty]
            }
        );
    }
    let h = OrderedHarness::new(
        Pattern::Repetition(
            Box::new(sym("A")),
            RepetitionQuantifier::ZeroOrMoreReluctant,
        ),
        &[("A", &[true, true])],
    );
    let mut ctx = initialized_scan_context(&h.matcher);
    h.drive(&mut ctx, true, 2, true, true);
    assert_eq!(h.labels(&ctx), [Sym::Empty]);
    assert!(!ctx.thread_store.has_in_flight_states_for_tier());
    assert_eq!(
        ctx.thread_store.node_arena.len(),
        1,
        "reluctant empty acceptance must not consume A"
    );
}

#[test]
fn open_head_end_anchor_promotes_only_at_virtual_eof() {
    for continuation in [false, true] {
        let h = OrderedHarness::new(
            Pattern::Alternation(vec![
                Pattern::Concat(vec![sym("A1"), Pattern::Symbol(Symbol::End)]),
                sym("A2"),
            ]),
            &[("A1", &[true, false]), ("A2", &[true, false])],
        );
        for yielding in [false, true] {
            let mut ctx = initialized_scan_context(&h.matcher);
            h.drive(&mut ctx, true, 1, false, yielding);
            assert_eq!(h.labels(&ctx), [Sym::from_index(2)]);
            assert_eq!(
                ctx.thread_store.buffers.as_ref().unwrap().active.len(),
                1,
                "unresolved A1 $ must survive ahead of A2"
            );
            h.drive(
                &mut ctx,
                false,
                if continuation { 2 } else { 1 },
                true,
                yielding,
            );
            assert_eq!(
                h.labels(&ctx),
                [Sym::from_index(if continuation { 2 } else { 1 })]
            );
            assert_eq!(ctx.scan_state.incumbent.unwrap().end_row, AbsoluteRow::ZERO);
        }
    }
}

#[test]
fn lane_retires_self_acceptance_and_final_physical_row_before_yield() {
    use crate::execution::matching::row_loop::lane_scan::{self, LaneCollection};
    let reluctant = || {
        Pattern::Repetition(Box::new(sym("A")), RepetitionQuantifier::OneOrMoreReluctant)
    };
    for (pattern, eof) in [
        (reluctant(), false),
        (
            Pattern::Concat(vec![Pattern::Symbol(Symbol::Start), reluctant()]),
            false,
        ),
        (
            Pattern::Concat(vec![
                sym("A"),
                Pattern::Repetition(
                    Box::new(sym("B")),
                    RepetitionQuantifier::AtMostOneReluctant,
                ),
            ]),
            false,
        ),
        (
            Pattern::Concat(vec![
                Pattern::Symbol(Symbol::Start),
                Pattern::Repetition(Box::new(sym("A")), RepetitionQuantifier::OneOrMore),
                Pattern::Symbol(Symbol::End),
            ]),
            true,
        ),
    ] {
        let h = OrderedHarness::with_compact_paths(
            pattern,
            &[("A", &[true]), ("B", &[false])],
            true,
        );
        let program = h
            .matcher
            .program
            .base_variant()
            .lane_scan_program()
            .expect("Lane admitted");
        for yielding in [false, true] {
            let mut ctx = initialized_scan_context(&h.matcher);
            let mut collection = LaneCollection::new();
            let mut session = test_session(&h.matcher, &h.provider, &h.input, &mut ctx);
            session.range.total_rows = 1 + usize::from(eof);
            session.range.read_end_row = 1;
            session.range.has_virtual_row = eof;
            session.yield_policy = if yielding {
                YieldPolicy::from_test_budget(1)
            } else {
                YieldPolicy::Disabled
            };
            lane_scan::start_local_candidate_scan(
                &h.matcher,
                program,
                session,
                &mut collection,
            )
            .unwrap();
            let lane = ctx.lane_scan_state().unwrap();
            assert_eq!(
                lane.active_len(),
                0,
                "acceptance must retire before any yield"
            );
            assert!(!lane.selection_is_open());
            assert_eq!(lane.incumbent().unwrap().end_row, AbsoluteRow::ZERO);
            assert_eq!(
                ctx.scan_state.current_row, 1,
                "do not spin through a virtual row"
            );
        }
    }
}