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.

//! Necessary final-row membership for complete, nonempty matches classified by Boolean inputs.

use super::fallible_vec::{filled, reserved};
use crate::core::SymbolId;
use crate::execution::matching::symbols::BoolColumnProvider;
use crate::nfa::{AnchorEnvironment, CompiledAutomaton};
use datafusion::common::Result;
use std::sync::Arc;

pub(crate) fn last_symbols(
    compiled: &CompiledAutomaton,
) -> Result<Option<Arc<[SymbolId]>>> {
    if compiled.min_match_rows() == 0 || !compiled.anchored_at_end() {
        return Ok(None);
    }
    let mut seen = filled(compiled.num_symbols(), false, "final-symbol marks")?;
    let mut symbols = reserved(compiled.num_symbols(), "final symbols")?;
    for state in compiled.nfa().states() {
        for (symbol, targets) in state.transition_rows() {
            if !seen[symbol.index()] {
                for &target in targets {
                    // After the final consuming edge, a nonempty match is at
                    // VirtualEnd. The existing closure handles optional suffixes
                    // and anchors. Unreachable edges only broaden this set.
                    let accepts = compiled
                        .accepting_preference_rank(
                            target,
                            Some(AnchorEnvironment::VirtualEnd),
                        )
                        .is_some();
                    if accepts {
                        seen[symbol.index()] = true;
                        symbols.push(symbol);
                        break;
                    }
                }
            }
        }
    }
    Ok(Some(Arc::from(symbols)))
}

pub(crate) fn can_finish(
    symbols: &[SymbolId],
    provider: &impl BoolColumnProvider,
    provider_origin: usize,
    end: usize,
    completed: &mut impl FnMut(usize) -> Result<()>,
) -> Result<bool> {
    let Some(row) = end
        .checked_sub(1)
        .and_then(|row| row.checked_sub(provider_origin))
    else {
        return Ok(true);
    };
    if row >= provider.num_rows() {
        return Ok(true);
    }
    let Some(location) = provider.locate_with_work(row, completed)? else {
        return Ok(true);
    };
    for &symbol in symbols {
        completed(1)?;
        if provider.get_bool_with_loc(symbol, location) {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Prove that starts away from `^` can only accept at `$`, and collect a
/// conservative alphabet covering every reachable consuming edge. Ignoring
/// possessive restrictions can only broaden the proof graph.
pub(crate) fn trailing_alphabet(compiled: &CompiledAutomaton) -> Result<Option<u64>> {
    if compiled.min_match_rows() == 0
        || !compiled.has_end_anchor()
        || compiled.num_symbols() > 64
    {
        return Ok(None);
    }
    let nfa = compiled.nfa();
    let mut seen = filled(nfa.state_count(), false, "suffix reachability")?;
    let mut queue = reserved(nfa.state_count(), "suffix states")?;
    let root = nfa.start_state();
    seen[root.index()] = true;
    queue.push(root);
    let mut cursor = 0;
    let mut mask = 0;
    while cursor < queue.len() {
        let state = queue[cursor];
        cursor += 1;
        if compiled
            .anchor_first_accepting_state(AnchorEnvironment::PhysicalInterior, state)
            .is_some()
        {
            return Ok(None);
        }
        for &dispatch in
            compiled.anchor_dispatch_closure(AnchorEnvironment::PhysicalInterior, state)
        {
            for (symbol, targets) in nfa.state(dispatch).transition_rows() {
                if targets.is_empty() {
                    continue;
                }
                let Some(bit) = symbol.packed_membership_bit() else {
                    return Ok(None);
                };
                mask |= bit;
                for &target in targets {
                    if !seen[target.index()] {
                        seen[target.index()] = true;
                        queue.push(target);
                    }
                }
            }
        }
    }
    Ok(Some(mask))
}