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.

//! Prove that expanded ordinary edges preserve Lane acceptance and ordering.
//! Graph cycles and history capacity are checked separately by Lane compilation.

use crate::execution::matching::row_loop::lane_scan::LaneBoundaryAnchors;
use crate::nfa::{AnchorEnvironment, CompiledAutomaton};
use crate::planning::SymbolRelationships;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ReachabilityRejection {
    Graph,
    Nullable,
    Capacity,
}

pub(crate) fn admission_with_anchors(
    compiled: &CompiledAutomaton,
    relationships: &SymbolRelationships,
    allow_empty_fallback: bool,
) -> Result<LaneBoundaryAnchors, ReachabilityRejection> {
    if compiled.has_anchors() {
        return admit_boundary_anchored(compiled);
    }
    let mut has_possessive_controls = false;
    for state in compiled.nfa().states() {
        has_possessive_controls |= !state.possessive_transition_controls().is_empty();
        for transition in state.epsilon_transitions() {
            if transition.predicate().is_some() {
                return Err(ReachabilityRejection::Graph);
            }
        }
    }
    if has_possessive_controls
        && !possessive_controls_are_redundant(compiled, relationships)
    {
        return Err(ReachabilityRejection::Graph);
    }
    // A consuming winner precedes the empty match only when root acceptance
    // is the final choice. Callers that require a consuming root reject every
    // nullable graph; the acceptance rank remains explicit in this proof.
    let root = compiled.nfa().start_state();
    if let Some(rank) = compiled.accepting_preference_rank(root, None)
        && (!allow_empty_fallback
            || rank == 0
            || rank != compiled.nfa().state(root).unconditional_dispatch().len())
    {
        return Err(ReachabilityRejection::Nullable);
    }
    if compiled.num_symbols() > 64 {
        return Err(ReachabilityRejection::Capacity);
    }
    Ok(LaneBoundaryAnchors::None)
}

/// Prove that anchors only restrict partition boundaries. Lane's evaluator
/// admission restricts partition-end acceptance to static predicates over
/// closed input. General retains patterns with anchor-dependent interior dispatch.
fn admit_boundary_anchored(
    compiled: &CompiledAutomaton,
) -> Result<LaneBoundaryAnchors, ReachabilityRejection> {
    if compiled.min_match_rows() == 0 {
        return Err(ReachabilityRejection::Graph);
    }
    if compiled.num_symbols() > 64 {
        return Err(ReachabilityRejection::Capacity);
    }
    let start_anchored = compiled.has_mandatory_start_anchor_prefix();
    let end_anchored = compiled.anchored_at_end();
    // Require a mandatory leading `^` so at most one start (row 0) exists per
    // partition, and reject optional or partial `$` where some paths accept
    // before EOF and others require `$`.
    if !start_anchored || (!end_anchored && compiled.has_end_anchor()) {
        return Err(ReachabilityRejection::Graph);
    }
    let nfa = compiled.nfa();
    let state_count = nfa.state_count();
    let start = nfa.start_state();
    // Non-nullable patterns must never accept before consuming a row.
    if compiled
        .anchor_first_accepting_state(AnchorEnvironment::PhysicalStart, start)
        .is_some()
        || compiled
            .anchor_first_accepting_state(AnchorEnvironment::PhysicalInterior, start)
            .is_some()
    {
        return Err(ReachabilityRejection::Graph);
    }
    for state in nfa.states() {
        if !state.possessive_transition_controls().is_empty() {
            return Err(ReachabilityRejection::Graph);
        }
    }

    // Collect every consuming-edge target reachable from `start` under
    // `PhysicalStart` at `start` and `PhysicalInterior` everywhere else.
    // Intermediate epsilon states between `start` and `^` are never active
    // LaneStates and are not constrained.
    let mut visited_target = Vec::new();
    visited_target
        .try_reserve_exact(state_count)
        .map_err(|_| ReachabilityRejection::Capacity)?;
    visited_target.resize(state_count, false);
    let mut queue = Vec::new();
    queue
        .try_reserve_exact(state_count)
        .map_err(|_| ReachabilityRejection::Capacity)?;
    let enqueue_targets = |source_id: crate::nfa::AutomatonStateId,
                           env: AnchorEnvironment,
                           visited: &mut [bool],
                           queue: &mut Vec<crate::nfa::AutomatonStateId>|
     -> bool {
        for &dispatch_id in compiled.anchor_dispatch_closure(env, source_id) {
            for (_, targets) in nfa.state(dispatch_id).transition_rows() {
                for &target in targets {
                    if target == start {
                        return false;
                    }
                    if !visited[target.index()] {
                        visited[target.index()] = true;
                        queue.push(target);
                    }
                }
            }
        }
        true
    };
    if !enqueue_targets(
        start,
        AnchorEnvironment::PhysicalStart,
        &mut visited_target,
        &mut queue,
    ) {
        return Err(ReachabilityRejection::Graph);
    }
    let mut cursor = 0;
    while cursor < queue.len() {
        let state_id = queue[cursor];
        cursor += 1;
        let interior_dispatch = compiled
            .anchor_dispatch_closure(AnchorEnvironment::PhysicalInterior, state_id);
        let interior_accept = compiled
            .anchor_first_accepting_state(AnchorEnvironment::PhysicalInterior, state_id);
        let interior_rank = compiled.accepting_preference_rank(
            state_id,
            Some(AnchorEnvironment::PhysicalInterior),
        );
        if compiled.anchor_dispatch_closure(AnchorEnvironment::PhysicalStart, state_id)
            != interior_dispatch
            || compiled
                .anchor_first_accepting_state(AnchorEnvironment::PhysicalStart, state_id)
                != interior_accept
            || compiled.accepting_preference_rank(
                state_id,
                Some(AnchorEnvironment::PhysicalStart),
            ) != interior_rank
        {
            return Err(ReachabilityRejection::Graph);
        }
        if compiled.anchor_dispatch_closure(AnchorEnvironment::VirtualEnd, state_id)
            != interior_dispatch
        {
            return Err(ReachabilityRejection::Graph);
        }
        if end_anchored {
            if interior_accept.is_some() {
                return Err(ReachabilityRejection::Graph);
            }
        } else if compiled
            .anchor_first_accepting_state(AnchorEnvironment::VirtualEnd, state_id)
            != interior_accept
            || compiled
                .accepting_preference_rank(state_id, Some(AnchorEnvironment::VirtualEnd))
                != interior_rank
        {
            return Err(ReachabilityRejection::Graph);
        }
        if !enqueue_targets(
            state_id,
            AnchorEnvironment::PhysicalInterior,
            &mut visited_target,
            &mut queue,
        ) {
            return Err(ReachabilityRejection::Graph);
        }
    }
    Ok(LaneBoundaryAnchors::Boundary { end_anchored })
}

/// An exit disjoint from every continuation can only consume rows the
/// continuation rejects. When the exit is non-nullable, or when every
/// consuming continuation edge immediately reaches an accepting state (such as
/// a single-row loop body before an optional suffix like `B++ C?`), suppressing
/// that exit adds no matching behavior, so the ordinary ordered edges preserve
/// the possessive decision.
fn possessive_controls_are_redundant(
    compiled: &CompiledAutomaton,
    relationships: &SymbolRelationships,
) -> bool {
    if compiled.num_symbols() > 64 {
        return false;
    }
    let mut disjoint = [0u64; 64];
    for (left, right) in &relationships.disjoint {
        let left = compiled
            .symbols_iter()
            .find(|(_, name)| name.eq_ignore_ascii_case(left));
        let right = compiled
            .symbols_iter()
            .find(|(_, name)| name.eq_ignore_ascii_case(right));
        if let (Some((left, _)), Some((right, _))) = (left, right) {
            disjoint[left.index()] |= 1u64 << right.index();
            disjoint[right.index()] |= 1u64 << left.index();
        }
    }

    let bitmaps = compiled.unconditional_closure_transition_bitmap();
    let accepting = compiled.unconditional_first_accepting_state();
    for state in compiled.nfa().states() {
        for control in state.possessive_transition_controls() {
            let mut continuing = bitmaps[control.continue_state().index()];
            let exiting = bitmaps[control.exit_state().index()];
            let exit_accepts = accepting[control.exit_state().index()].is_some();
            if continuing == 0
                || (exiting == 0 && !exit_accepts)
                || continuing & exiting != 0
            {
                return false;
            }
            if exit_accepts {
                for &dispatch_id in compiled
                    .nfa()
                    .state(control.continue_state())
                    .unconditional_dispatch()
                {
                    for (_, targets) in
                        compiled.nfa().state(dispatch_id).transition_rows()
                    {
                        for &target in targets {
                            if accepting[target.index()].is_none() {
                                return false;
                            }
                        }
                    }
                }
            }
            while continuing != 0 {
                let symbol = continuing.trailing_zeros() as usize;
                continuing &= continuing - 1;
                if exiting & !disjoint[symbol] != 0 {
                    return false;
                }
            }
        }
    }
    true
}