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::*;
use crate::core::{NormalizedPattern, Pattern, Symbol};

#[test]
fn sparse_dispatch_preserves_the_first_ordered_edge_across_acceptance() {
    // Use a sealed state ID, then arrange its edges to exercise a duplicated
    // high bit on both sides of acceptance. The real graph reserves symbol
    // slot zero, but the sparse index itself accepts all 64 packed bit positions.
    let compiled = CompiledAutomaton::compile(
        &NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into()))),
        &["A".into()],
    )
    .unwrap();
    let state = compiled.nfa().start_state();
    let labels = [63, 7, 1, 63, 5, 9];
    let mut edges = labels
        .iter()
        .enumerate()
        .map(|(i, &shift)| OrderedTransitionEdge {
            source_state_id: state,
            symbol_id: SymbolId::try_new(1 + usize::from(shift), 65).unwrap(),
            next_state_id: state,
            excluded: false,
            packed_shift: shift,
            after_accept: i >= 3,
            symbol_dispatch: OrderedTransitionEdge::NO_OFFSET
                | if shift == 63 {
                    OrderedTransitionEdge::SHARES_SYMBOL
                } else {
                    0
                },
        })
        .collect::<Vec<_>>();
    let required = labels
        .iter()
        .fold(0u64, |mask, shift| mask | (1u64 << shift));

    // A filtered dispatch graph leaves its slots unindexed. Test that as well
    // as the sealed index, with a nonzero range start and an empty final state.
    for indexed in [false, true] {
        if indexed {
            seal_symbol_offsets(&mut edges, required);
        }
        let mut storage = vec![edges[0]];
        storage.extend_from_slice(&edges);
        let range = 1..storage.len();
        let table = OrderedTransitionTable {
            start_state: state,
            ranges: Box::new([range.clone()]),
            edges: storage.into_boxed_slice(),
        };
        let mask = if indexed {
            required
        } else {
            required | (1 << 3)
        };
        for combination in 0..64 {
            let enabled = [1, 3, 5, 7, 9, 63]
                .iter()
                .enumerate()
                .filter(|(i, _)| combination & (1 << i) != 0)
                .fold(0u64, |word, (_, shift)| word | (1u64 << shift))
                & mask;
            let ordered = labels
                .iter()
                .position(|shift| enabled & (1u64 << shift) != 0);
            let id = table.first_enabled_edge(range.clone(), mask, enabled);
            assert_eq!(id, ordered.map(|i| range.start + i));
            if let Some(id) = id {
                let edge = table.sealed_edge(id);
                let i = ordered.unwrap();
                assert_eq!(edge.after_accept, i >= 3);
                assert_eq!(edge.shares_symbol(), labels[i] == 63);
            }
            // With a winner, both lower-priority labels together must stop at
            // acceptance. A duplicate before acceptance must instead replay.
            let lower_priority_labels = (1 << 5) | (1 << 9);
            if enabled == lower_priority_labels || enabled == 1 << 63 {
                let edge = table.sealed_edge(id.unwrap());
                assert_eq!(edge.after_accept, enabled == lower_priority_labels);
                assert!(edge.shares_symbol() || !enabled.is_power_of_two());
            }
            assert_eq!(
                table.first_enabled_edge(range.end..range.end, mask, enabled),
                None
            );
        }
    }
}

// Three word-sized fields and four packed flags determine the retained size,
// which is also what the transition table's reservation charges.
#[test]
fn dispatch_edge_has_compact_retained_size() {
    let word = size_of::<usize>();
    assert_eq!(
        size_of::<OrderedTransitionEdge>(),
        (3 * word + 4).next_multiple_of(word)
    );
}