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 lane successor retention and priority-ordered acceptance laws.

use super::state::{LaneScanState, LaneSuccessorAction, LaneView};
use crate::core::{AbsoluteRow, PhysicalRowCount};
use crate::execution::matching::{PatternMatcher, state_set::check_state_equivalence};
use crate::nfa::CompiledAutomaton;
use datafusion::common::{DataFusionError, Result};

/// Publish the staged scratch lane and report whether acceptance closes this row.
///
/// Active lanes and edges are visited in strict SQL:2016 lexical priority order
/// (PikeVM ordered threads):
/// - Any already-staged equivalent successor at the same state strictly outranks
///   the new candidate and causes it to be discarded.
/// - Any accepting transition strictly outranks any earlier incumbent, replaces
///   it unconditionally, retires the rest of the current row, and retains the
///   successor only when higher-priority continuations exist (`accept_rank > 0`)
///   and physical input remains (a partition-end acceptance cannot continue).
#[inline]
pub(in crate::execution::matching) fn commit_scratch_transition(
    matcher: &PatternMatcher,
    compiled: &CompiledAutomaton,
    lane: &mut LaneScanState,
    row: AbsoluteRow,
    retains: bool,
    can_accept: bool,
    completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<bool> {
    let program = &lane.program;
    let scratch = lane.scratch();
    let acceptance = if can_accept {
        match program.closure_accepting[scratch.state.state_id.index()] {
            Some(accepting) => Some((
                accepting,
                row.checked_add(PhysicalRowCount::new(1))
                    .ok_or_else(overflow)?,
            )),
            None => None,
        }
    } else {
        None
    };

    let dominated_by_self_accept = acceptance.is_some()
        && (program.requires_partition_end()
            || compiled.accepting_preference_rank(
                scratch.state.state_id,
                program.accept_environment(),
            ) == Some(0));

    let action = if !retains || dominated_by_self_accept {
        LaneSuccessorAction::Discard
    } else {
        let mut found_equivalent = false;
        for index in 0..lane.successor_len() {
            completed(1)?;
            let previous = lane
                .successor_state(index)
                .expect("successor index is sealed");
            if previous.state_id == scratch.state.state_id
                && equivalent(
                    matcher,
                    compiled,
                    lane.candidate_start().expect("live lane candidate"),
                    scratch,
                    lane.successor(index).expect("successor index is sealed"),
                    completed,
                )?
            {
                found_equivalent = true;
                break;
            }
        }
        if found_equivalent {
            LaneSuccessorAction::Discard
        } else {
            LaneSuccessorAction::Append
        }
    };

    let publication = lane.plan_publication(action, acceptance, row)?;
    completed(publication.work)?;
    lane.publish_scratch(publication);
    Ok(publication.row_complete)
}

fn overflow() -> DataFusionError {
    DataFusionError::ResourcesExhausted(
        "MATCH_RECOGNIZE lane acceptance position overflow".into(),
    )
}

fn equivalent(
    matcher: &PatternMatcher,
    compiled: &CompiledAutomaton,
    match_start: AbsoluteRow,
    left: LaneView<'_>,
    right: LaneView<'_>,
    completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<bool> {
    check_state_equivalence(
        match_start,
        match_start,
        left.state.state_id,
        compiled.nfa().state(left.state.state_id).is_accepting(),
        compiled,
        matcher.program.aggregate_symbols_bitmap(),
        !matcher.program.has_path_dependent_aggregates(),
        completed,
        |completed| {
            completed(1)?;
            if left.registers != right.registers {
                completed(1)?;
                return Ok(false);
            }
            let equivalent = left.navigation == right.navigation;
            completed(left.navigation.len().max(1))?;
            Ok(equivalent)
        },
    )
}