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.

use super::EpsilonClosureScratch;
use crate::core::{NormalizedPattern, Pattern, RepetitionQuantifier, Symbol, SymbolId};
use crate::execution::common::memory::new_unbounded_state_memory;
use crate::nfa::{AutomatonStateId, CompiledAutomaton};
use datafusion::common::DataFusionError;
use datafusion::execution::memory_pool::{GreedyMemoryPool, MemoryConsumer, MemoryPool};
use std::sync::Arc;

fn possessive_automaton() -> (CompiledAutomaton, AutomatonStateId) {
    let pattern = Pattern::Concat(vec![
        Pattern::Repetition(
            Box::new(Pattern::Symbol(Symbol::Named("A".into()))),
            RepetitionQuantifier::OneOrMorePossessive,
        ),
        Pattern::Symbol(Symbol::Named("A".into())),
    ]);
    let normalized_pattern = NormalizedPattern::Ast(pattern);
    let compiled = CompiledAutomaton::compile(&normalized_pattern, &["A".into()])
        .expect("possessive test pattern should compile");
    let possessive_slot = compiled
        .nfa()
        .states()
        .position(|state| !state.possessive_transition_controls().is_empty())
        .expect("possessive test pattern should expose pruning controls");
    let possessive_state = compiled
        .nfa()
        .state_id(possessive_slot)
        .expect("possessive control owner is a sealed state");
    (compiled, possessive_state)
}

#[test]
fn possessive_callback_error_advances_generation_before_scratch_reuse() {
    let (automaton, state_id) = possessive_automaton();
    let compiled = &automaton;
    let matched_symbols = [SymbolId::try_new(1, compiled.num_symbols()).unwrap()];
    let memory = new_unbounded_state_memory();
    let mut scratch = EpsilonClosureScratch::new(&memory);
    let initial_generation = scratch.generation.current();

    let error = scratch
        .compute(compiled, state_id, 1 << 1, &matched_symbols, &mut |_| {
            Err(DataFusionError::Execution("stop".into()))
        })
        .expect_err("callback should stop the possessive traversal");
    assert!(matches!(error, DataFusionError::Execution(message) if message == "stop"));
    assert_eq!(scratch.generation.current(), initial_generation + 1);

    let mut completed_units = 0;
    scratch
        .compute(compiled, state_id, 1 << 1, &matched_symbols, &mut |units| {
            completed_units += units;
            Ok(())
        })
        .expect("reused possessive scratch should succeed");
    let reused_out = scratch.tmp.clone();
    assert!(completed_units > reused_out.len());
    assert_eq!(scratch.generation.current(), initial_generation + 2);

    let mut fresh = EpsilonClosureScratch::new(&memory);
    fresh
        .compute(
            compiled,
            state_id,
            1 << 1,
            &matched_symbols,
            &mut |_| Ok(()),
        )
        .expect("fresh possessive scratch should succeed");

    assert!(fresh.tmp.len() > 1);
    assert_eq!(reused_out, fresh.tmp);
}

#[test]
fn possessive_closure_keeps_scratch_accounted_on_pool_denial() {
    let (automaton, state_id) = possessive_automaton();
    let matched_symbols = [SymbolId::try_new(1, automaton.num_symbols()).unwrap()];
    let state_bytes = size_of::<AutomatonStateId>();
    let marks_bytes = automaton.nfa().state_count() * size_of::<u32>();
    for (capacity, stack_bytes, denied_storage) in [
        (0, 0, "traversal visited state"),
        (marks_bytes, 0, "possessive closure stack"),
        (
            marks_bytes + state_bytes,
            state_bytes,
            "possessive closure output",
        ),
    ] {
        let pool = Arc::new(GreedyMemoryPool::new(capacity));
        let memory = MemoryConsumer::new("possessive-closure-test")
            .register(&(Arc::clone(&pool) as Arc<dyn MemoryPool>));
        let mut scratch = EpsilonClosureScratch::new(&memory);
        let initial_generation = scratch.generation.current();
        let error = scratch
            .compute(&automaton, state_id, 1 << 1, &matched_symbols, &mut |_| {
                Ok(())
            })
            .expect_err("closure must admit each allocation");
        assert!(
            matches!(error, DataFusionError::ResourcesExhausted(ref message)
            if message.contains(denied_storage))
        );
        assert!(scratch.tmp.is_empty());
        assert!(scratch.stack.is_empty());
        assert_eq!(
            scratch.generation.current(),
            initial_generation + u32::from(capacity != 0)
        );
        assert_eq!(scratch.stack.capacity() * state_bytes, stack_bytes);
        assert_eq!(pool.reserved(), capacity);
        drop(scratch);
        assert_eq!(pool.reserved(), 0);
    }
}

#[test]
fn possessive_control_resolves_a_wide_symbol_before_cutting_a_distinct_exit() {
    let mut names: Vec<_> = (1..=64).map(|i| format!("P{i}")).collect();
    names.extend(["A".into(), "B".into()]);
    let sym = |name: &str| Pattern::Symbol(Symbol::Named(name.into()));
    let pattern = Pattern::Concat(vec![
        Pattern::Repetition(
            Box::new(sym("A")),
            RepetitionQuantifier::ZeroOrMorePossessive,
        ),
        Pattern::Alternation(vec![sym("A"), sym("B")]),
    ]);
    let nfa =
        CompiledAutomaton::compile(&NormalizedPattern::Ast(pattern), &names).unwrap();
    // The possessive split belongs to the consuming loop's tail; the
    // zero-length entry of A* has an ordinary epsilon bypass.
    let split = nfa
        .nfa()
        .states()
        .position(|state| !state.possessive_transition_controls().is_empty())
        .and_then(|index| nfa.nfa().state_id(index))
        .unwrap();
    let a = SymbolId::try_new(65, nfa.num_symbols()).unwrap();
    let b = SymbolId::try_new(66, nfa.num_symbols()).unwrap();
    let target = *nfa
        .nfa()
        .state(split)
        .unconditional_dispatch()
        .iter()
        .find(|&&id| !nfa.nfa().state(id).transitions(b).is_empty())
        .unwrap();
    let mut closure = EpsilonClosureScratch::new(&new_unbounded_state_memory());
    for a_matches in [false, true] {
        let matched = if a_matches { vec![a, b] } else { vec![b] };
        closure
            .compute(&nfa, split, 0, &matched, &mut |_| Ok(()))
            .unwrap();
        assert_eq!(closure.tmp.contains(&target), !a_matches);
    }
}

#[test]
fn closure_uses_dfs_preference_instead_of_numeric_state_order() {
    let sym = |name: &str| Pattern::Symbol(Symbol::Named(name.into()));
    let pattern = Pattern::Alternation(vec![
        Pattern::Repetition(Box::new(sym("A")), RepetitionQuantifier::ZeroOrMore),
        sym("B"),
    ]);
    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(pattern),
        &["A".into(), "B".into()],
    )
    .unwrap();
    let mut scratch = EpsilonClosureScratch::new(&new_unbounded_state_memory());
    scratch
        .compute(&compiled, compiled.nfa().start_state(), 0, &[], &mut |_| {
            Ok(())
        })
        .unwrap();
    let dispatch: Vec<_> = scratch
        .tmp
        .iter()
        .copied()
        .filter(|&id| compiled.nfa().state(id).transition_bitmap() != 0)
        .collect();
    assert_eq!(
        dispatch,
        compiled
            .nfa()
            .state(compiled.nfa().start_state())
            .unconditional_dispatch()
    );
    assert!(
        scratch.tmp.windows(2).any(|pair| pair[0] > pair[1]),
        "fixture must distinguish DFS from numeric sorting"
    );
    let (offset, accepting) = scratch.first_accepting.unwrap();
    assert_eq!(scratch.tmp[offset], accepting);
    assert!(
        offset
            < scratch
                .tmp
                .iter()
                .position(
                    |&id| compiled.nfa().state(id).transition_bitmap() & (1 << 2) != 0
                )
                .unwrap()
    );
}

#[test]
fn pruned_possessive_exit_preserves_acceptance_before_later_alternative() {
    let sym = |name: &str| Pattern::Symbol(Symbol::Named(name.into()));
    let pattern = Pattern::Alternation(vec![
        Pattern::Repetition(
            Box::new(Pattern::Concat(vec![sym("A"), sym("B")])),
            RepetitionQuantifier::ZeroOrMorePossessive,
        ),
        sym("C"),
    ]);
    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(pattern),
        &["A".into(), "B".into(), "C".into()],
    )
    .unwrap();
    let mut scratch = EpsilonClosureScratch::new(&new_unbounded_state_memory());
    let a = SymbolId::try_new(1, compiled.num_symbols()).unwrap();
    let c = SymbolId::try_new(3, compiled.num_symbols()).unwrap();
    // At entry, empty acceptance precedes C; at the possessive loop tail the
    // exit is pruned, but its stopping position must still cut off lower work.
    let split = compiled
        .nfa()
        .states()
        .position(|state| !state.possessive_transition_controls().is_empty())
        .unwrap();
    for root in [
        compiled.nfa().start_state(),
        compiled.nfa().state_id(split).unwrap(),
    ] {
        scratch
            .compute(&compiled, root, (1 << 1) | (1 << 3), &[a, c], &mut |_| {
                Ok(())
            })
            .unwrap();
        let (offset, accepting) = scratch
            .first_accepting
            .expect("pruning must retain stopping priority");
        assert!(compiled.nfa().state(accepting).is_accepting());
        assert!(
            scratch.tmp[..offset].iter().any(|&id| compiled
                .nfa()
                .state(id)
                .transition_bitmap()
                & (1 << 1)
                != 0)
        );
        assert!(
            scratch.tmp[..offset].iter().all(|&id| compiled
                .nfa()
                .state(id)
                .transition_bitmap()
                & (1 << 3)
                == 0)
        );
        if root.index() == split {
            assert!(
                !scratch.tmp.contains(&accepting),
                "fixture must actually prune the accepting exit"
            );
        }
    }
}