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.

//! Shared test-only preference model, calibrated against recorded Trino answers.
//!
//! Enabled only by the non-default `test-support` feature. Consumers should
//! enable it in dev-dependencies; ordinary runtime builds contain no model.
//!
//! It builds its own graph directly from `Pattern` and deliberately imports no
//! production compiler, path, closure, or comparer. It implements the same
//! proposed ordering rule, so external calibration remains necessary: this is an
//! independent implementation, not an independent definition of SQL semantics.

use crate::core::{Pattern, Symbol};

/// One selected output row, including an empty-match marker.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OutputRow {
    /// Partition-relative input position; `rows.len()` denotes partition end.
    pub row: usize,
    /// One-based match number within the partition.
    pub match_number: usize,
    /// One-based row position within this match; empty markers use one.
    pub sequence: usize,
    /// Selected symbol, or `None` for an empty match.
    pub classifier: Option<String>,
}

#[derive(Clone, Copy)]
enum Guard {
    Always,
    Start,
    End,
}

#[derive(Default)]
struct State {
    consume: Option<(String, usize)>,
    epsilon: Vec<(usize, Guard)>,
    accept: bool,
    loop_back_target: Option<usize>,
}

#[derive(Default)]
struct Graph {
    states: Vec<State>,
}

impl Graph {
    fn state(&mut self) -> usize {
        let index = self.states.len();
        self.states.push(State::default());
        index
    }

    fn edge(&mut self, from: usize, to: usize) {
        self.states[from].epsilon.push((to, Guard::Always));
    }

    fn build(&mut self, pattern: &Pattern) -> (usize, usize) {
        match pattern {
            Pattern::Symbol(symbol) => {
                let start = self.state();
                let end = self.state();
                match symbol {
                    Symbol::Named(name) => {
                        self.states[start].consume = Some((name.clone(), end));
                    }
                    Symbol::Start => self.states[start].epsilon.push((end, Guard::Start)),
                    Symbol::End => self.states[start].epsilon.push((end, Guard::End)),
                }
                (start, end)
            }
            Pattern::Group(inner) => self.build(inner),
            Pattern::Concat(parts) => {
                let start = self.state();
                let mut end = start;
                for part in parts {
                    let (next, tail) = self.build(part);
                    self.edge(end, next);
                    end = tail;
                }
                (start, end)
            }
            Pattern::Alternation(parts) => {
                let start = self.state();
                let end = self.state();
                for part in parts {
                    let (head, tail) = self.build(part);
                    self.edge(start, head);
                    self.edge(tail, end);
                }
                (start, end)
            }
            Pattern::Repetition(inner, quantifier) => {
                let bounds = quantifier.bounds();
                assert!(
                    !bounds.is_possessive(),
                    "reference does not model possessive pruning"
                );
                let start = self.state();
                let mut tail = start;
                let mut last_head = None;
                for _ in 0..bounds.min {
                    let (head, end) = self.build(inner);
                    self.edge(tail, head);
                    tail = end;
                    last_head = Some(head);
                }
                let exit = self.state();
                match bounds.max {
                    Some(max) => {
                        for _ in bounds.min..max {
                            let (head, end) = self.build(inner);
                            if bounds.is_reluctant() {
                                self.edge(tail, exit);
                                self.edge(tail, head);
                            } else {
                                self.edge(tail, head);
                                self.edge(tail, exit);
                            }
                            tail = end;
                        }
                        self.edge(tail, exit);
                    }
                    None => {
                        let loop_head = if let Some(head) = last_head {
                            head
                        } else {
                            let (head, end) = self.build(inner);
                            if bounds.is_reluctant() {
                                self.edge(start, exit);
                            }
                            self.edge(start, head);
                            tail = end;
                            if !bounds.is_reluctant() {
                                self.edge(start, exit);
                            }
                            head
                        };
                        if bounds.is_reluctant() {
                            self.edge(tail, exit);
                            self.edge(tail, loop_head);
                        } else {
                            self.edge(tail, loop_head);
                            self.edge(tail, exit);
                        }
                        self.states[tail].loop_back_target = Some(loop_head);
                    }
                }
                (start, exit)
            }
            Pattern::Exclude(_) | Pattern::Permute(_) => {
                panic!("reference covers ordinary choices, repetitions, and anchors")
            }
        }
    }

    fn outcomes(&self, state: usize, position: usize, end: usize) -> Vec<usize> {
        enum Frame {
            Enter(usize),
            Finish(usize),
        }
        let mut emitted = vec![false; self.states.len()];
        let mut finished = vec![false; self.states.len()];
        let mut on_stack = vec![0usize; self.states.len()];
        let mut stack = vec![Frame::Enter(state)];
        let mut outcomes = Vec::new();
        while let Some(frame) = stack.pop() {
            match frame {
                Frame::Finish(index) => {
                    on_stack[index] -= 1;
                    finished[index] = true;
                }
                Frame::Enter(index) => {
                    if finished[index] {
                        continue;
                    }
                    let state = &self.states[index];
                    if !std::mem::replace(&mut emitted[index], true)
                        && (state.consume.is_some() || state.accept)
                    {
                        outcomes.push(index);
                    }
                    on_stack[index] += 1;
                    stack.push(Frame::Finish(index));
                    for &(target, guard) in state.epsilon.iter().rev() {
                        let allowed = match guard {
                            Guard::Always => true,
                            Guard::Start => position == 0,
                            Guard::End => position == end,
                        };
                        if allowed
                            && !(state.loop_back_target == Some(target)
                                && on_stack[target] > 0)
                            && !finished[target]
                        {
                            stack.push(Frame::Enter(target));
                        }
                    }
                }
            }
        }
        outcomes
    }
}

#[derive(Clone)]
struct Thread {
    state: usize,
    key: Vec<usize>,
    path: Vec<(usize, String)>,
}

fn attempt(graph: &Graph, start: usize, rows: &[&str], origin: usize) -> Option<Thread> {
    let mut threads = vec![Thread {
        state: start,
        key: Vec::new(),
        path: Vec::new(),
    }];
    let mut best: Option<Thread> = None;
    for position in origin..=rows.len() {
        let mut next: Vec<Option<Thread>> = vec![None; graph.states.len()];
        for thread in threads {
            for (rank, outcome) in graph
                .outcomes(thread.state, position, rows.len())
                .into_iter()
                .enumerate()
            {
                let mut candidate = thread.clone();
                candidate.key.push(rank);
                let state = &graph.states[outcome];
                if state.accept {
                    if best.as_ref().is_none_or(|old| candidate.key < old.key) {
                        best = Some(candidate);
                    }
                } else if let Some((name, target)) = &state.consume
                    && position < rows.len()
                    && rows[position].contains(name.as_str())
                {
                    candidate.state = *target;
                    candidate.path.push((position, name.clone()));
                    if next[*target]
                        .as_ref()
                        .is_none_or(|old| candidate.key < old.key)
                    {
                        next[*target] = Some(candidate);
                    }
                }
            }
        }
        threads = next.into_iter().flatten().collect();
        if threads.is_empty() {
            break;
        }
    }
    best
}

/// Which positions may begin a match.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EndPolicy {
    /// Trino's calibrated behavior: starts are physical input rows.
    PhysicalRows,
    /// Include the zero-width start after the final row of a nonempty partition.
    PartitionEnd,
}

/// Enumerate `SKIP PAST LAST ROW`, `ALL ROWS SHOW EMPTY` matches using Trino's
/// physical-start policy. Call [`all_matches_with_policy`] to include the
/// partition-end start explicitly.
#[cfg(test)]
pub fn all_matches(pattern: &Pattern, rows: &[&str]) -> Vec<OutputRow> {
    all_matches_with_policy(pattern, rows, EndPolicy::PhysicalRows)
}

/// Enumerate matches within one partition, resetting all anchor coordinates.
/// Truth rows contain the matched symbols from `A`, `B`, and `C` (for example
/// `"AC"`). A terminal empty row has `row == rows.len()`. Empty input has no partition.
pub fn all_matches_with_policy(
    pattern: &Pattern,
    rows: &[&str],
    policy: EndPolicy,
) -> Vec<OutputRow> {
    let mut graph = Graph::default();
    let (start, end) = graph.build(pattern);
    let sink = graph.state();
    graph.states[sink].accept = true;
    graph.edge(end, sink);
    let mut output = Vec::new();
    let mut origin = 0;
    let mut match_number = 0;
    while origin < rows.len() {
        let Some(selected) = attempt(&graph, start, rows, origin) else {
            origin += 1;
            continue;
        };
        match_number += 1;
        if selected.path.is_empty() {
            output.push(OutputRow {
                row: origin,
                match_number,
                sequence: 1,
                classifier: None,
            });
            origin += 1;
        } else {
            origin = selected.path.last().unwrap().0 + 1;
            output.extend(selected.path.into_iter().enumerate().map(
                |(index, (row, classifier))| OutputRow {
                    row,
                    match_number,
                    sequence: index + 1,
                    classifier: Some(classifier),
                },
            ));
        }
    }
    if policy == EndPolicy::PartitionEnd
        && !rows.is_empty()
        && attempt(&graph, start, rows, rows.len()).is_some()
    {
        output.push(OutputRow {
            row: rows.len(),
            match_number: match_number + 1,
            sequence: 1,
            classifier: None,
        });
    }
    output
}

/// Advance the fixed-seed generator used by bounded reference checks.
#[cfg(test)]
pub fn next(seed: &mut u64, bound: u64) -> u64 {
    *seed ^= *seed << 13;
    *seed ^= *seed >> 7;
    *seed ^= *seed << 17;
    *seed % bound
}

/// Generate ordinary choices and mixed greedy/reluctant repetitions, without
/// possessive markers.
#[cfg(test)]
pub fn generated_pattern(seed: &mut u64, depth: usize) -> Pattern {
    use crate::core::RepetitionQuantifier;
    if depth == 0 {
        return Pattern::Symbol(Symbol::Named(
            ["A", "B", "C"][next(seed, 3) as usize].into(),
        ));
    }
    match next(seed, 7) {
        kind @ 0..=3 => {
            let inner = generated_pattern(seed, depth - 1);
            let quantifier = match kind {
                0 => RepetitionQuantifier::AtMostOne,
                1 => RepetitionQuantifier::ZeroOrMore,
                2 => RepetitionQuantifier::OneOrMore,
                _ => RepetitionQuantifier::Range(1, 2),
            };
            let quantifier = if next(seed, 2) == 0 {
                quantifier
            } else {
                quantifier.reluctant_variant().unwrap()
            };
            repeat(inner, quantifier)
        }
        4 => Pattern::Concat(vec![
            generated_pattern(seed, depth - 1),
            generated_pattern(seed, depth - 1),
        ]),
        5 => Pattern::Alternation(vec![
            generated_pattern(seed, depth - 1),
            generated_pattern(seed, depth - 1),
        ]),
        _ => generated_pattern(seed, 0),
    }
}

#[cfg(test)]
fn repeat(pattern: Pattern, quantifier: crate::core::RepetitionQuantifier) -> Pattern {
    Pattern::Repetition(Box::new(pattern), quantifier)
}