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.

//! Required symbol occurrences and their row offsets on accepting paths.

use super::{Pattern, Symbol, SymbolMappings, resolve_symbol_id};
use crate::core::RepetitionQuantifier;
use smallvec::SmallVec;

/// Maximum number of positional clauses retained for one automaton.
pub const MAX_REQUIRED_ANCHORS: usize = 8;

/// Every accepting path consumes a symbol in `mask` at a row in these inclusive
/// bounds, relative to the match start. Separate clauses can use different rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RequiredAnchor {
    /// User-symbol membership bits (symbol 1 occupies bit 0).
    pub mask: u64,
    /// Minimum number of consumed rows before the occurrence.
    pub min_before: usize,
    /// Maximum number of consumed rows before the occurrence, if bounded.
    pub max_before: Option<usize>,
}

impl RequiredAnchor {
    fn shifted(self, min: usize, max: Option<usize>) -> Self {
        Self {
            mask: self.mask,
            min_before: min.saturating_add(self.min_before),
            max_before: max.and_then(|n| n.checked_add(self.max_before?)),
        }
    }

    fn either(self, rhs: Self) -> Self {
        Self {
            mask: self.mask | rhs.mask,
            min_before: self.min_before.min(rhs.min_before),
            max_before: self.max_before.zip(rhs.max_before).map(|(a, b)| a.max(b)),
        }
    }

    fn priority(self) -> (bool, bool) {
        (self.mask.is_power_of_two(), self.max_before.is_some())
    }
}

#[derive(Debug, Default)]
pub(super) struct RequiredSymbols {
    pub(super) mask: u64,
    pub(super) anchors: SmallVec<[RequiredAnchor; MAX_REQUIRED_ANCHORS]>,
}

impl RequiredSymbols {
    fn keep(&mut self, anchor: RequiredAnchor) {
        if self.anchors.contains(&anchor) {
            return;
        }
        if self.anchors.len() < MAX_REQUIRED_ANCHORS {
            self.anchors.push(anchor);
        } else if let Some(weakest) = self.anchors.iter_mut().min_by_key(|c| c.priority())
            && weakest.priority() < anchor.priority()
        {
            *weakest = anchor;
        }
    }
}

struct Facts {
    min: usize,
    max: Option<usize>,
    required: RequiredSymbols,
}

impl Facts {
    fn fixed(rows: usize, mask: u64) -> Self {
        let mut required = RequiredSymbols {
            mask,
            ..Default::default()
        };
        // A PERMUTE can place each required symbol anywhere in its consumed span.
        let mut bits = mask;
        while bits != 0 && required.anchors.len() < MAX_REQUIRED_ANCHORS {
            let bit = 1 << bits.trailing_zeros();
            required.keep(RequiredAnchor {
                mask: bit,
                min_before: 0,
                max_before: Some(rows - 1),
            });
            bits ^= bit;
        }
        Self {
            min: rows,
            max: Some(rows),
            required,
        }
    }

    fn then(&mut self, rhs: Self) {
        for anchor in rhs.required.anchors {
            self.required.keep(anchor.shifted(self.min, self.max));
        }
        self.required.mask |= rhs.required.mask;
        self.min = self.min.saturating_add(rhs.min);
        self.max = self.max.and_then(|n| n.checked_add(rhs.max?));
    }

    fn either(&mut self, rhs: Self) {
        let left = std::mem::take(&mut self.required.anchors);
        let right = &rhs.required.anchors;
        self.required.mask &= rhs.required.mask;
        self.min = self.min.min(rhs.min);
        self.max = self.max.zip(rhs.max).map(|(a, b)| a.max(b));
        for a in &left {
            if a.mask.is_power_of_two()
                && let Some(b) = right.iter().find(|b| b.mask == a.mask)
            {
                self.required.keep(a.either(*b));
            }
        }
        if let (Some(a), Some(b)) = (left.first(), right.first()) {
            self.required.keep(a.either(*b));
        }
    }

    fn repeat(&mut self, q: &RepetitionQuantifier) {
        let copies = q.min_repetitions() as usize;
        if copies == 0 {
            self.required = RequiredSymbols::default();
        } else if copies > 1 && self.min > 0 {
            // The first and last mandatory copies can prove disjoint intervals
            // for the same symbol, e.g. B at offsets 1 and 2 in A B{2}.
            let previous = copies - 1;
            let min = self.min.saturating_mul(previous);
            let max = self.max.and_then(|n| n.checked_mul(previous));
            for anchor in self.required.anchors.clone() {
                self.required.keep(anchor.shifted(min, max));
            }
        }
        self.min = self.min.saturating_mul(copies);
        self.max = match (self.max, q.max_repetitions()) {
            (Some(0), _) | (_, Some(0)) => Some(0),
            (Some(n), Some(copies)) => n.checked_mul(copies as usize),
            _ => None,
        };
    }
}

/// Stream siblings into their parent so storage depends on depth, not fan-out.
pub(super) fn analyze(mut node: &Pattern, mappings: &SymbolMappings) -> RequiredSymbols {
    let membership = |symbol: &Symbol| match symbol {
        Symbol::Named(name) => resolve_symbol_id(name, mappings)
            .and_then(|id| id.packed_membership_bit())
            .unwrap_or(0),
        Symbol::Start | Symbol::End => 0,
    };
    struct Frame<'a> {
        pattern: &'a Pattern,
        rest: std::slice::Iter<'a, Pattern>,
        prior: Option<Facts>,
    }
    let mut parents = Vec::new();
    'visit: loop {
        let mut facts = match node {
            Pattern::Symbol(s) | Pattern::Exclude(s) => {
                Facts::fixed(usize::from(matches!(s, Symbol::Named(_))), membership(s))
            }
            Pattern::Permute(symbols) => {
                let mut bits = 0;
                let mut rows = 0;
                for symbol in symbols {
                    rows += usize::from(matches!(symbol, Symbol::Named(_)));
                    bits |= membership(symbol);
                }
                Facts::fixed(rows, bits)
            }
            Pattern::Concat(parts) | Pattern::Alternation(parts) if parts.is_empty() => {
                Facts::fixed(0, 0)
            }
            _ => {
                let (first, rest) = match node {
                    Pattern::Group(inner) | Pattern::Repetition(inner, _) => {
                        (inner.as_ref(), [].as_slice())
                    }
                    Pattern::Concat(parts) | Pattern::Alternation(parts) => {
                        (&parts[0], &parts[1..])
                    }
                    _ => unreachable!(),
                };
                parents.push(Frame {
                    pattern: node,
                    rest: rest.iter(),
                    prior: None,
                });
                node = first;
                continue;
            }
        };
        loop {
            let Some(frame) = parents.last_mut() else {
                return facts.required;
            };
            if let Some(mut prior) = frame.prior.take() {
                if matches!(frame.pattern, Pattern::Concat(_)) {
                    prior.then(facts);
                } else {
                    prior.either(facts);
                }
                facts = prior;
            }
            if let Some(next) = frame.rest.next() {
                frame.prior = Some(facts);
                node = next;
                continue 'visit;
            }
            if let Pattern::Repetition(_, q) = frame.pattern {
                facts.repeat(q);
            }
            parents.pop();
        }
    }
}