datafusion-match-recognize 0.55.0

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.

//! Decides whether the input head has enough rows to commit or replay.

use super::*;
use crate::core::{EmptyMatchesMode, NavigationOffset, RowsPerMatch};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Boundary {
    NeedPrecedence,
    NeedNext,
    Commit,
    NoMatch,
}

pub(super) fn resolve_boundary(
    final_input: bool,
    at_head_end: bool,
    selection_is_open: bool,
    incumbent_end: Option<AbsoluteRow>,
    readable_end: PhysicalEndExclusive,
    next: NavigationOffset,
) -> Result<Boundary> {
    let waiting_for_next = if let Some(end) = incumbent_end {
        let readable = readable_end.position();
        if end >= readable {
            return internal_err!(
                "MATCH_RECOGNIZE incumbent end {end} reaches or exceeds its readable boundary {readable_end} (final input: {final_input})"
            );
        }
        let required = end.checked_add(PhysicalRowCount::new(next.as_u64())).ok_or_else(|| {
            DataFusionError::ResourcesExhausted("MATCH_RECOGNIZE NEXT output boundary cannot be represented as an absolute row".into())
        })?;
        !final_input && !next.is_zero() && required >= readable
    } else {
        false
    };
    let open = !final_input && selection_is_open;
    if (open || waiting_for_next) && !at_head_end {
        return internal_err!(
            "MATCH_RECOGNIZE invalid scan boundary facts (reject.future_away_from_head)"
        );
    }
    Ok(if open {
        Boundary::NeedPrecedence
    } else if waiting_for_next {
        Boundary::NeedNext
    } else if incumbent_end.is_some() {
        Boundary::Commit
    } else {
        Boundary::NoMatch
    })
}

pub(super) fn validate_unmatched_retention(
    rows_per_match: &RowsPerMatch,
    unmatched_retention_floor: Option<AbsoluteRow>,
) -> Result<()> {
    let with_unmatched = matches!(
        rows_per_match,
        RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched)
    );
    match (with_unmatched, unmatched_retention_floor) {
        (true, Some(_)) | (false, None) => Ok(()),
        (true, None) => internal_err!(
            "MATCH_RECOGNIZE WITH UNMATCHED requires a row-presence retention floor"
        ),
        (false, Some(_)) => internal_err!(
            "MATCH_RECOGNIZE row-presence retention floor requires WITH UNMATCHED"
        ),
    }
}

pub(super) fn resolve_physical_head(
    candidate_end: PhysicalEndExclusive,
    readable_end: PhysicalEndExclusive,
    physical_backing_end: PhysicalEndExclusive,
) -> Result<bool> {
    if candidate_end > readable_end {
        return internal_err!(
            "MATCH_RECOGNIZE candidate-start range end {} exceeds readable input end {}",
            candidate_end,
            readable_end
        );
    }
    if readable_end > physical_backing_end {
        return internal_err!(
            "MATCH_RECOGNIZE readable input end {} exceeds physical backing end {}",
            readable_end,
            physical_backing_end
        );
    }
    Ok(readable_end == physical_backing_end)
}

#[cfg(test)]
mod tests {
    use super::super::candidates::checked_provider_row;
    use super::*;
    use crate::core::{NormalizedPattern, Pattern, Symbol};
    use crate::execution::matching::path::{PathStep, Sym};
    use crate::execution::storage::accumulator::{
        SelectedPathFillOrder, SelectedPathValidator,
    };
    use crate::nfa::CompiledAutomaton;

    #[test]
    fn scan_boundary_decisions_respect_live_precedence_and_output_lookahead() {
        let end = PhysicalEndExclusive::new(AbsoluteRow::new(112));
        for (final_input, open, incumbent, offset, expected) in [
            (false, true, Some(110), 0, Boundary::NeedPrecedence),
            (false, true, None, 0, Boundary::NeedPrecedence),
            (false, false, Some(110), 2, Boundary::NeedNext),
            (false, false, Some(111), 0, Boundary::Commit),
            (false, false, Some(110), 1, Boundary::Commit),
            (true, true, Some(111), 2, Boundary::Commit),
            (true, true, None, 0, Boundary::NoMatch),
            (false, false, None, 0, Boundary::NoMatch),
        ] {
            let incumbent = incumbent.map(AbsoluteRow::new);
            let next = NavigationOffset::try_new(offset).unwrap();
            assert_eq!(
                resolve_boundary(final_input, true, open, incumbent, end, next).unwrap(),
                expected
            );
            if matches!(expected, Boundary::NeedNext | Boundary::NeedPrecedence) {
                assert!(
                    resolve_boundary(final_input, false, open, incumbent, end, next)
                        .unwrap_err()
                        .to_string()
                        .contains("reject.future_away_from_head")
                );
            }
        }
    }

    #[test]
    fn boundary_fact_resolvers_check_coordinates_navigation_and_output_policy() {
        let row = AbsoluteRow::new;
        let end = |value| PhysicalEndExclusive::new(row(value));
        for (candidate, readable, backing, expected) in [
            (110, 120, 120, Ok(true)),
            (110, 119, 120, Ok(false)),
            (121, 120, 122, Err("candidate-start range end")),
            (110, 121, 120, Err("readable input end")),
        ] {
            let actual =
                resolve_physical_head(end(candidate), end(readable), end(backing));
            match expected {
                Ok(value) => assert_eq!(actual.unwrap(), value),
                Err(fragment) => {
                    let error = actual.unwrap_err();
                    assert!(matches!(error, DataFusionError::Internal(_)));
                    assert!(error.to_string().contains(fragment), "{error}");
                }
            }
        }
        for (final_input, incumbent, offset, expected) in [
            (false, None, 1, Boundary::NoMatch),
            (false, Some(110), 0, Boundary::Commit),
            (false, Some(110), 9, Boundary::Commit),
            (false, Some(110), 10, Boundary::NeedNext),
            (true, Some(110), 10, Boundary::Commit),
            (true, Some(119), 1, Boundary::Commit),
            (true, Some(119), 0, Boundary::Commit),
        ] {
            assert_eq!(
                resolve_boundary(
                    final_input,
                    true,
                    false,
                    incumbent.map(row),
                    end(120),
                    NavigationOffset::try_new(offset).unwrap()
                )
                .unwrap(),
                expected
            );
        }
        for (final_input, incumbent) in [(false, 120), (true, 120), (true, 121)] {
            let error = resolve_boundary(
                final_input,
                true,
                false,
                Some(row(incumbent)),
                end(120),
                NavigationOffset::ZERO,
            )
            .unwrap_err();
            assert!(matches!(error, DataFusionError::Internal(_)));
            assert!(
                error
                    .to_string()
                    .contains(&format!("incumbent end {incumbent} reaches or exceeds")),
                "final_input={final_input}, incumbent={incumbent}: {error}"
            );
        }
        for mode in [
            RowsPerMatch::OneRow,
            RowsPerMatch::AllRows(EmptyMatchesMode::Show),
            RowsPerMatch::AllRows(EmptyMatchesMode::Omit),
        ] {
            validate_unmatched_retention(&mode, None).unwrap();
        }
        let with_unmatched = RowsPerMatch::AllRows(EmptyMatchesMode::WithUnmatched);
        validate_unmatched_retention(&with_unmatched, Some(row(95))).unwrap();
        for (mode, floor, fragment) in [
            (with_unmatched, None, "WITH UNMATCHED requires"),
            (
                RowsPerMatch::OneRow,
                Some(row(95)),
                "retention floor requires WITH UNMATCHED",
            ),
        ] {
            let error = validate_unmatched_retention(&mode, floor).unwrap_err();
            assert!(matches!(error, DataFusionError::Internal(_)));
            assert!(error.to_string().contains(fragment), "{error}");
        }
    }

    #[test]
    fn stale_absolute_cursor_is_not_aliased_to_provider_row_zero() {
        let error = checked_provider_row(4, 5, "test cursor")
            .expect_err("a stale cursor must fail checked conversion");
        assert!(
            error
                .to_string()
                .contains("row 4 precedes provider origin 5")
        );
    }

    #[test]
    fn nfa_selected_match_preserves_resolution_and_acceptance_position() {
        let compiled = CompiledAutomaton::compile(
            &NormalizedPattern::Ast(Pattern::Symbol(Symbol::Named("A".into()))),
            &["A".into(), "B".into()],
        )
        .unwrap();
        let steps = [(10, 1), (11, 2), (13, 2), (14, 1)]
            .map(|(row, symbol)| PathStep {
                row: AbsoluteRow::new(row),
                sym: Sym::from_index(symbol),
                excluded: false,
            })
            .to_vec();
        let checked_path = |acceptance_position| {
            let mut validator = SelectedPathValidator::try_new(
                &compiled,
                &EmptyMatchesMode::Show,
                true,
                &(10..15),
                10,
                5,
                SelectedPathFillOrder::Forward,
            )
            .unwrap();
            for &step in &steps {
                validator.observe(step).unwrap();
            }
            validator
                .finish(
                    steps.clone(),
                    AbsoluteRow::new(10),
                    AbsoluteRow::new(14),
                    acceptance_position,
                )
                .unwrap()
        };
        for (final_input, acceptance) in [(true, 14), (false, 15)] {
            assert_eq!(
                resolve_boundary(
                    final_input,
                    true,
                    false,
                    Some(AbsoluteRow::new(14)),
                    PhysicalEndExclusive::new(AbsoluteRow::new(15)),
                    NavigationOffset::ZERO
                )
                .unwrap(),
                Boundary::Commit
            );
            // Acceptance can be after the last consumed row, as for compact scans.
            let acceptance = AbsoluteRow::new(acceptance);
            let path = checked_path(acceptance);
            assert_eq!(path.steps(), steps.as_slice());
            let cursor = path
                .next_cursor(
                    &crate::execution::matching::ResolvedAfterMatchSkip::PastLastRow,
                    path.semantic_start(),
                    None,
                )
                .unwrap();
            assert_eq!(cursor.row_idx, 15);
        }
    }
}