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.

//! Stateless scans for MATCH_RECOGNIZE classifier masks.
//! Null mask entries count as non-matches.

use std::collections::VecDeque;

use datafusion::arrow::array::{Array, BooleanArray};
use datafusion::common::{DataFusionError, Result};

/// Find the `offset`-th (0-indexed) match without allocating an index table.
pub(super) fn nth_first_match_index(
    mask_arr: &BooleanArray,
    offset: usize,
) -> Option<usize> {
    mask_arr
        .iter()
        .enumerate()
        .filter_map(|(index, matched)| (matched == Some(true)).then_some(index))
        .nth(offset)
}

/// Scan `mask_arr` in a single pass for `0..num_rows`, mapping each row's
/// `offset`-th prior-or-equal match index (`offset == 0` is the nearest match)
/// without retaining a per-row cache vector.
pub(super) fn map_nth_last_matches(
    mask_arr: &BooleanArray,
    num_rows: usize,
    offset: usize,
    mut map: impl FnMut(Option<usize>) -> Option<usize>,
) -> Result<Vec<Option<usize>>> {
    if num_rows > mask_arr.len() {
        return Err(DataFusionError::Internal(format!(
            "MATCH_RECOGNIZE classifier-mask index {} is outside {} cached rows",
            mask_arr.len(),
            mask_arr.len(),
        )));
    }
    let mut out = Vec::with_capacity(num_rows);
    if offset == 0 {
        let mut last_match = None;
        for i in 0..num_rows {
            if mask_arr.is_valid(i) && mask_arr.value(i) {
                last_match = Some(i);
            }
            out.push(map(last_match));
        }
        return Ok(out);
    }
    if offset >= num_rows {
        for _ in 0..num_rows {
            out.push(map(None));
        }
        return Ok(out);
    }
    // Never preallocate `offset + 1` capacity: `window` only grows as true
    // entries are encountered and never exceeds `offset + 1 <= num_rows`.
    let window_size = offset + 1;
    let mut window = VecDeque::new();
    for i in 0..num_rows {
        if mask_arr.is_valid(i) && mask_arr.value(i) {
            if window.len() == window_size {
                window.pop_front();
            }
            window.push_back(i);
        }
        let anchor = (window.len() == window_size).then(|| window[0]);
        out.push(map(anchor));
    }
    Ok(out)
}

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

    #[test]
    fn first_match_finds_present_and_missing_anchors() {
        let mask = BooleanArray::from(vec![None, Some(false), Some(true), Some(true)]);
        assert_eq!(nth_first_match_index(&mask, 0), Some(2));
        assert_eq!(nth_first_match_index(&mask, 1), Some(3));
        assert_eq!(nth_first_match_index(&mask, usize::MAX), None);

        let no_match = BooleanArray::from(vec![None, Some(false)]);
        assert_eq!(nth_first_match_index(&no_match, 0), None);
    }

    #[test]
    fn map_nearest_matches_checks_bounds_and_tracks_last_true() {
        let mask = BooleanArray::from(vec![None, Some(true), Some(false), Some(true)]);
        let mapped = map_nth_last_matches(&mask, 4, 0, |anchor| anchor).unwrap();
        assert_eq!(mapped, vec![None, Some(1), Some(1), Some(3)]);

        let err = map_nth_last_matches(&mask, 5, 0, |anchor| anchor).unwrap_err();
        assert!(err.to_string().contains("outside 4 cached rows"), "{err}");
    }
}