datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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.

//! PERMUTE pattern compilation utilities.
//!
//! PERMUTE(A, B, C, ...) lowers to a precedence-preserving prefix tree of
//! possible orderings. Each choice point uses the standard alternation compiler,
//! so lexicographic ordering of the input positions still determines which
//! symbol is consumed first when multiple orderings are possible.
//!
//! The number of complete orderings is still factorial, so compilation rejects
//! `PERMUTE` inputs whose deduplicated branch count exceeds the configured
//! limit. The prefix tree avoids duplicating common prefixes in
//! the compiled NFA, reducing state growth for larger accepted PERMUTE inputs.

use super::super::compiler::NfaBuilder;
use super::cost::validate_permutation_branch_count;
use crate::core::{Pattern, Symbol};
use datafusion_common::{DataFusionError, Result};
use std::collections::HashMap;

#[derive(Clone)]
struct PermuteEntry {
    symbol: Symbol,
    positions: Vec<usize>,
}

fn collect_entries(symbols: &[Symbol]) -> Vec<PermuteEntry> {
    let mut entry_by_symbol = HashMap::<Symbol, usize>::new();
    let mut entries = Vec::<PermuteEntry>::new();
    for (position, symbol) in symbols.iter().cloned().enumerate() {
        let entry_idx = if let Some(&idx) = entry_by_symbol.get(&symbol) {
            idx
        } else {
            let idx = entries.len();
            entries.push(PermuteEntry {
                symbol: symbol.clone(),
                positions: Vec::new(),
            });
            entry_by_symbol.insert(symbol, idx);
            idx
        };
        entries[entry_idx].positions.push(position);
    }
    entries
}

fn build_candidates(entries: &[PermuteEntry], used_counts: &[usize]) -> Vec<usize> {
    let mut candidates = entries
        .iter()
        .enumerate()
        .filter_map(|(idx, entry)| {
            entry
                .positions
                .get(used_counts[idx])
                .map(|position| (*position, idx))
        })
        .collect::<Vec<_>>();
    candidates.sort_by_key(|(position, _)| *position);
    candidates.into_iter().map(|(_, idx)| idx).collect()
}

fn concat_pair(head: Pattern, tail: Pattern) -> Pattern {
    match tail {
        Pattern::Concat(mut parts) => {
            parts.insert(0, head);
            Pattern::Concat(parts)
        }
        other => Pattern::Concat(vec![head, other]),
    }
}

fn build_permutation_prefix_tree(
    entries: &[PermuteEntry],
    used_counts: &mut [usize],
    remaining: usize,
) -> Pattern {
    debug_assert!(remaining > 0);

    let candidates = build_candidates(entries, used_counts);
    if let [entry_idx] = candidates.as_slice() {
        if remaining == 1 {
            let symbol = Pattern::Symbol(entries[*entry_idx].symbol.clone());

            return symbol;
        }
        // One remaining symbol kind can still have a long run. Build it flat
        // instead of recursively prepending and cloning the growing suffix.
        // Counts stay unchanged, matching the recursive path's restored state.
        let mut parts = Vec::with_capacity(remaining);
        for _ in 0..remaining {
            parts.push(Pattern::Symbol(entries[*entry_idx].symbol.clone()));
        }
        return Pattern::Concat(parts);
    }
    let mut branches = Vec::with_capacity(candidates.len());
    for entry_idx in candidates {
        used_counts[entry_idx] += 1;
        let head = Pattern::Symbol(entries[entry_idx].symbol.clone());
        let branch = concat_pair(
            head,
            build_permutation_prefix_tree(entries, used_counts, remaining - 1),
        );
        used_counts[entry_idx] -= 1;
        branches.push(branch);
    }
    Pattern::Alternation(branches)
}

/// Attach a PERMUTE pattern to the main `NfaBuilder` and return `(start, end)`
/// state IDs inside the builder's arena.
///
/// This function lowers PERMUTE(A, B, C, ...) into a nested alternation that
/// shares common prefixes between possible orderings while preserving SQL
/// leftmost precedence semantics.
pub(crate) fn attach_permute(
    b: &mut NfaBuilder,
    symbols: &[Symbol],
) -> Result<(usize, usize)> {
    if symbols.is_empty() {
        return Err(DataFusionError::Plan(
            "MATCH_RECOGNIZE PERMUTE pattern must contain at least one symbol".into(),
        ));
    }

    validate_permutation_branch_count(symbols, b.limits(), b.pattern_display())?;

    let entries = collect_entries(symbols);
    let mut used_counts = vec![0usize; entries.len()];
    let pattern =
        build_permutation_prefix_tree(&entries, &mut used_counts, symbols.len());

    b.build_pattern(&pattern)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn named_symbols(names: &[&str]) -> Vec<Symbol> {
        names
            .iter()
            .map(|name| Symbol::Named((*name).to_string()))
            .collect()
    }

    fn render_orderings(pattern: &Pattern) -> Vec<String> {
        match pattern {
            Pattern::Symbol(symbol) => vec![symbol.to_string()],
            Pattern::Concat(parts) => {
                let mut prefixes = vec![String::new()];
                for part in parts {
                    let suffixes = render_orderings(part);
                    prefixes = prefixes
                        .into_iter()
                        .flat_map(|prefix| {
                            suffixes.iter().map(move |suffix| {
                                let mut rendered = prefix.clone();
                                rendered.push_str(suffix);
                                rendered
                            })
                        })
                        .collect();
                }
                prefixes
            }
            Pattern::Alternation(branches) => {
                branches.iter().flat_map(render_orderings).collect()
            }
            Pattern::Group(inner) => render_orderings(inner),
            other => panic!("unexpected pattern in ordering test: {other:?}"),
        }
    }

    #[test]
    fn generated_orders_preserve_first_appearance_and_deduplicate() {
        for (names, expected) in [
            (vec!["A", "B", "A"], vec!["ABA", "AAB", "BAA"]),
            (vec!["B", "A", "A"], vec!["BAA", "ABA", "AAB"]),
            (vec!["A"; 8], vec!["AAAAAAAA"]),
        ] {
            let symbols = named_symbols(&names);
            let entries = collect_entries(&symbols);
            let mut used_counts = vec![0; entries.len()];
            let generated =
                build_permutation_prefix_tree(&entries, &mut used_counts, symbols.len());
            assert_eq!(render_orderings(&generated), expected, "{names:?}");
            assert!(used_counts.iter().all(|&count| count == 0));
        }
    }
}