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.

//! Checked input columns, symbol bindings, and selected-match skip policy.

use super::path::PathStep;
use crate::core::{AbsoluteRow, AfterMatchSkip, PhysicalRowCount, SymbolId};
use crate::execution::common::coordinates::absolute_row_to_usize;
use crate::nfa::CompiledAutomaton;
use datafusion::common::{DataFusionError, Result, internal_err};

/// Input-schema column checked while the executable program is constructed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct ResolvedInputColumn(usize);

impl ResolvedInputColumn {
    pub(crate) const fn new_validated(index: usize) -> Self {
        Self(index)
    }

    pub(crate) const fn index(self) -> usize {
        self.0
    }
}

/// Boolean input column whose existence and Arrow type were checked while the
/// executable program was constructed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct ResolvedBoolColumn(ResolvedInputColumn);

impl ResolvedBoolColumn {
    pub(crate) const fn new_validated(index: usize) -> Self {
        Self(ResolvedInputColumn::new_validated(index))
    }

    /// Return the DataFusion input-schema index stored in this handle.
    pub(crate) const fn index(self) -> usize {
        self.0.index()
    }
}

#[derive(Debug, Clone)]
pub(crate) struct SymbolColumn {
    pub(crate) id: SymbolId,
    pub(crate) column: ResolvedBoolColumn,
}

#[derive(Debug)]
pub(crate) struct SymbolTable {
    pub(crate) columns: Vec<SymbolColumn>,
}

impl SymbolTable {
    pub fn columns(&self) -> &[SymbolColumn] {
        &self.columns
    }

    /// Retain transition-live columns for the compiled automaton.
    pub(crate) fn try_transition_live(
        automaton: &CompiledAutomaton,
        columns: &[SymbolColumn],
    ) -> Result<Self> {
        let symbol_count = automaton.num_symbols();
        let mut live = Vec::with_capacity(columns.len());
        for column in columns {
            let column_id = column.id;
            if column_id.index() == 0 || column_id.index() >= symbol_count {
                return internal_err!(
                    "MATCH_RECOGNIZE active symbol column ID {} is outside the compiled domain of {symbol_count} slots",
                    column_id.index()
                );
            }
            let transition_live = (0..automaton.nfa().state_count()).any(|state_index| {
                let state_id = automaton
                    .nfa()
                    .state_id(state_index)
                    .expect("scan index is inside the sealed state domain");
                !automaton
                    .nfa()
                    .state(state_id)
                    .transitions(column_id)
                    .is_empty()
            });
            if transition_live {
                live.push(column.clone());
            }
        }
        Ok(Self { columns: live })
    }
}

#[derive(Clone, Debug)]
pub(crate) enum ResolvedAfterMatchSkip {
    PastLastRow,
    ToNextRow,
    ToFirst { symbol_id: SymbolId, name: String },
    ToLast { symbol_id: SymbolId, name: String },
}

impl ResolvedAfterMatchSkip {
    pub(crate) fn try_new(
        clause: &AfterMatchSkip,
        target: Option<SymbolId>,
    ) -> Result<Self> {
        let resolved = match clause {
            AfterMatchSkip::PastLastRow if target.is_none() => Some(Self::PastLastRow),
            AfterMatchSkip::ToNextRow if target.is_none() => Some(Self::ToNextRow),
            AfterMatchSkip::ToFirst(name) => target.map(|symbol_id| Self::ToFirst {
                symbol_id,
                name: name.clone(),
            }),
            AfterMatchSkip::ToLast(name) => target.map(|symbol_id| Self::ToLast {
                symbol_id,
                name: name.clone(),
            }),
            AfterMatchSkip::PastLastRow | AfterMatchSkip::ToNextRow => None,
        };
        resolved.ok_or_else(|| {
            DataFusionError::Internal(
                "MATCH_RECOGNIZE AFTER MATCH SKIP target is inconsistent".to_owned(),
            )
        })
    }
}

/// Authoritative outer collection cursor after a candidate finishes.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct NextMatchCursor {
    pub(crate) row_idx: usize,
}

#[cfg(test)]
#[expect(
    clippy::items_after_test_module,
    reason = "cursor tests stay beside cursor planning"
)]
mod tests {
    use super::NextMatchCursor;
    use crate::core::{AbsoluteRow, SymbolId};
    use crate::execution::matching::ResolvedAfterMatchSkip;

    #[test]
    fn selected_cursor_planning_checks_skip_targets_and_absolute_bounds() {
        let start = AbsoluteRow::new(10);
        let end = AbsoluteRow::new(13);
        let symbol_target = AbsoluteRow::new(12);
        let b = SymbolId::try_new(2, 3).unwrap();
        for (skip, target, first, last, expected) in [
            (ResolvedAfterMatchSkip::ToNextRow, None, start, end, Ok(11)),
            (
                ResolvedAfterMatchSkip::PastLastRow,
                None,
                start,
                end,
                Ok(14),
            ),
            (
                ResolvedAfterMatchSkip::ToFirst {
                    symbol_id: b,
                    name: "B".into(),
                },
                Some(symbol_target),
                start,
                end,
                Ok(12),
            ),
            (
                ResolvedAfterMatchSkip::ToLast {
                    symbol_id: b,
                    name: "B".into(),
                },
                Some(symbol_target),
                start,
                end,
                Ok(12),
            ),
            (
                ResolvedAfterMatchSkip::ToFirst {
                    symbol_id: b,
                    name: "B".into(),
                },
                Some(start),
                start,
                end,
                Err("does not advance"),
            ),
            (
                ResolvedAfterMatchSkip::ToNextRow,
                None,
                AbsoluteRow::MAX,
                AbsoluteRow::MAX,
                Err("maximum absolute row number"),
            ),
            (
                ResolvedAfterMatchSkip::PastLastRow,
                None,
                start,
                AbsoluteRow::MAX,
                Err("maximum absolute row number"),
            ),
        ] {
            let result = skip.plan_selected_cursor(first, last, false, target);
            match expected {
                Ok(row_idx) => assert_eq!(result.unwrap(), NextMatchCursor { row_idx }),
                Err(message) => {
                    let error = result.unwrap_err();
                    assert!(error.to_string().contains(message), "{error}");
                }
            }
        }
    }
}

impl ResolvedAfterMatchSkip {
    #[inline]
    pub(crate) fn advance_row(best_end_row: AbsoluteRow) -> Result<usize> {
        let next = best_end_row
            .checked_add(PhysicalRowCount::new(1))
            .ok_or_else(|| {
                DataFusionError::ResourcesExhausted(
                    "MATCH_RECOGNIZE next scan row exceeds the maximum absolute row number"
                        .to_string(),
                )
            })?;
        absolute_row_to_usize(next, "next scan row")
    }

    pub(crate) fn cursor_after(row: AbsoluteRow) -> Result<NextMatchCursor> {
        Ok(NextMatchCursor {
            row_idx: Self::advance_row(row)?,
        })
    }

    /// Retain the restart row while observing an already selected path.
    /// Row bounds handle both forward fills and reverse Arena reconstruction.
    #[inline]
    pub(crate) fn observe_selected_step(
        &self,
        step: PathStep,
        target: &mut Option<AbsoluteRow>,
    ) {
        match self {
            Self::ToFirst { symbol_id, .. }
                if step.sym.to_index() == symbol_id.index() =>
            {
                *target = Some(target.map_or(step.row, |row| row.min(step.row)));
            }
            Self::ToLast { symbol_id, .. }
                if step.sym.to_index() == symbol_id.index() =>
            {
                *target = Some(target.map_or(step.row, |row| row.max(step.row)));
            }
            _ => {}
        }
    }

    pub(crate) fn plan_selected_cursor(
        &self,
        match_start_row: AbsoluteRow,
        match_end_row: AbsoluteRow,
        is_empty: bool,
        symbol_target_row: Option<AbsoluteRow>,
    ) -> Result<NextMatchCursor> {
        let mut cursor = Self::cursor_after(match_start_row)?;

        // Empty matches advance exactly one row independently of the configured
        // non-empty skip target.
        if is_empty {
            return Ok(cursor);
        }

        match self {
            Self::PastLastRow => {
                cursor = Self::cursor_after(match_end_row)?;
            }
            Self::ToNextRow => {}
            Self::ToFirst { name, .. } | Self::ToLast { name, .. } => {
                let target_label = match self {
                    Self::ToFirst { .. } => "FIRST",
                    Self::ToLast { .. } => "LAST",
                    Self::PastLastRow | Self::ToNextRow => unreachable!(),
                };
                let target_row = symbol_target_row.ok_or_else(|| {
                    DataFusionError::Execution(format!(
                        "AFTER MATCH SKIP TO {target_label} {name}: symbol not found in match"
                    ))
                })?;
                if target_row <= match_start_row {
                    return datafusion::common::exec_err!(
                        "AFTER MATCH SKIP TO {} {}: skip target at row {} does not advance past the first row {} of the match",
                        target_label,
                        name,
                        target_row,
                        match_start_row
                    );
                }
                cursor.row_idx = absolute_row_to_usize(target_row, "symbol skip target")?;
            }
        }
        Ok(cursor)
    }
}