datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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.

//! Opaque, immutable NFA graph states, transitions, and anchors.

use crate::core::SymbolId;
use std::fmt;

/// Checked identity of one state in a sealed automaton.
///
/// Compilation creates state IDs only after it has checked the complete dense
/// state arena. Runtime code may extract the index once when entering a hot
/// loop and continue with direct slice indexing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct AutomatonStateId(usize);

impl AutomatonStateId {
    pub(crate) const fn try_new(index: usize, state_count: usize) -> Option<Self> {
        if index < state_count {
            Some(Self(index))
        } else {
            None
        }
    }

    /// Wrap an index after the consuming sealer has validated its graph domain.
    #[inline]
    pub(crate) const fn from_validated(index: usize, state_count: usize) -> Self {
        debug_assert!(index < state_count);
        Self(index)
    }

    /// Return this state's dense index in the sealed automaton.
    #[inline]
    pub const fn index(self) -> usize {
        self.0
    }
}

impl fmt::Display for AutomatonStateId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.0.fmt(f)
    }
}

/// One epsilon transition in a sealed automaton.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct EpsilonTransition {
    target: AutomatonStateId,
    predicate: Option<AnchorPredicate>,
}

impl EpsilonTransition {
    pub(crate) const fn new(
        target: AutomatonStateId,
        predicate: Option<AnchorPredicate>,
    ) -> Self {
        Self { target, predicate }
    }

    /// Destination state reached without consuming a row.
    #[inline]
    pub const fn target(self) -> AutomatonStateId {
        self.target
    }

    /// Optional input-position condition for this transition.
    #[inline]
    pub const fn predicate(self) -> Option<AnchorPredicate> {
        self.predicate
    }
}

/// Runtime control metadata for a possessive split point.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PossessiveTransitionControl {
    continue_state: AutomatonStateId,
    exit_state: AutomatonStateId,
}

impl PossessiveTransitionControl {
    pub(crate) const fn new(
        continue_state: AutomatonStateId,
        exit_state: AutomatonStateId,
    ) -> Self {
        Self {
            continue_state,
            exit_state,
        }
    }

    /// Preferred branch that continues the possessive repetition.
    #[inline]
    pub const fn continue_state(self) -> AutomatonStateId {
        self.continue_state
    }

    /// Exit branch suppressed when the continuation can consume the row.
    #[inline]
    pub const fn exit_state(self) -> AutomatonStateId {
        self.exit_state
    }
}

#[derive(Debug, Clone, Copy)]
pub(crate) struct StateDescriptor {
    is_accepting: bool,
    is_excluded: bool,
    transition_bitmap: u64,
}

impl StateDescriptor {
    pub(crate) const fn new(
        is_accepting: bool,
        is_excluded: bool,
        transition_bitmap: u64,
    ) -> Self {
        Self {
            is_accepting,
            is_excluded,
            transition_bitmap,
        }
    }
}

#[derive(Debug)]
pub(crate) struct PackedRows<T> {
    offsets: Box<[usize]>,
    values: Box<[T]>,
}

impl<T> PackedRows<T> {
    pub(crate) fn new(offsets: Vec<usize>, values: Vec<T>) -> Self {
        debug_assert!(!offsets.is_empty());
        debug_assert_eq!(offsets.last().copied(), Some(values.len()));
        Self {
            offsets: offsets.into_boxed_slice(),
            values: values.into_boxed_slice(),
        }
    }

    #[inline]
    fn row(&self, index: usize) -> &[T] {
        &self.values[self.offsets[index]..self.offsets[index + 1]]
    }
}

/// Borrowed view of one immutable state in a sealed pattern automaton.
///
/// The view keeps its state descriptor paired with the graph that owns all
/// variable-length state relations. Copying it does not copy graph data.
#[derive(Clone, Copy)]
pub struct CompiledStateRef<'a> {
    nfa: &'a NFA,
    id: AutomatonStateId,
    descriptor: &'a StateDescriptor,
}

impl fmt::Debug for CompiledStateRef<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CompiledStateRef")
            .field("id", &self.id)
            .field("descriptor", self.descriptor)
            .finish_non_exhaustive()
    }
}

impl<'a> CompiledStateRef<'a> {
    /// Whether entering this state completes a match.
    #[inline]
    pub const fn is_accepting(self) -> bool {
        self.descriptor.is_accepting
    }

    /// Whether rows consumed from this state are excluded from output.
    #[inline]
    pub const fn is_excluded(self) -> bool {
        self.descriptor.is_excluded
    }

    /// Bitmap of row-consuming transitions for the first 64 symbol slots.
    #[inline]
    pub const fn transition_bitmap(self) -> u64 {
        self.descriptor.transition_bitmap
    }

    /// Ordered destinations for one user symbol.
    ///
    /// `symbol` must belong to this automaton's stable symbol domain. Sealing
    /// guarantees that every user-symbol row exists, so the hot lookup is a
    /// direct dense index rather than a repeated bounds check.
    #[inline]
    pub fn transitions(self, symbol: SymbolId) -> &'a [AutomatonStateId] {
        self.nfa.transition_row(self.id, symbol.index())
    }

    /// User-symbol transition rows in stable symbol-table order.
    #[inline]
    pub fn transition_rows(
        self,
    ) -> impl ExactSizeIterator<Item = (SymbolId, &'a [AutomatonStateId])> + Clone + 'a
    {
        let slot_count = self.nfa.symbol_slot_count;
        (1..slot_count).map(move |index| {
            let symbol = SymbolId::try_new(index, slot_count)
                .expect("non-zero sealed transition slots are user symbols");
            (symbol, self.nfa.transition_row(self.id, index))
        })
    }

    /// Dense transition rows for compiler-owned graph analysis.
    #[inline]
    pub(crate) fn transition_slots(
        self,
    ) -> impl ExactSizeIterator<Item = &'a [AutomatonStateId]> + Clone + 'a {
        (0..self.nfa.symbol_slot_count)
            .map(move |index| self.nfa.transition_row(self.id, index))
    }

    /// Epsilon transitions in compiler-defined encounter order.
    #[inline]
    pub fn epsilon_transitions(self) -> &'a [EpsilonTransition] {
        self.nfa.epsilon_transitions.row(self.id.index())
    }

    /// Row-consuming states in preferred DFS order through the unconditional
    /// epsilon closure. Acceptance has a separate insertion rank.
    #[inline]
    pub fn unconditional_dispatch(self) -> &'a [AutomatonStateId] {
        self.nfa.unconditional_dispatch.row(self.id.index())
    }

    /// Possessive continue/exit controls originating at this state.
    #[inline]
    pub fn possessive_transition_controls(self) -> &'a [PossessiveTransitionControl] {
        self.nfa.possessive_transition_controls.row(self.id.index())
    }
}

/// Read-only owner of a sealed dense NFA graph.
///
/// State descriptors and variable-length graph relations use flat immutable
/// buffers. [`CompiledStateRef`] couples a descriptor to this owner and exposes
/// the corresponding relation slices without allocating.
#[allow(clippy::upper_case_acronyms)]
#[derive(Debug)]
pub struct NFA {
    states: Box<[StateDescriptor]>,
    symbol_slot_count: usize,
    transitions: PackedRows<AutomatonStateId>,
    epsilon_transitions: PackedRows<EpsilonTransition>,
    unconditional_dispatch: PackedRows<AutomatonStateId>,
    possessive_transition_controls: PackedRows<PossessiveTransitionControl>,
    start_state: AutomatonStateId,
    source_payload_floor_bytes: usize,
}

impl NFA {
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn new(
        states: Vec<StateDescriptor>,
        symbol_slot_count: usize,
        transitions: PackedRows<AutomatonStateId>,
        epsilon_transitions: PackedRows<EpsilonTransition>,
        unconditional_dispatch: PackedRows<AutomatonStateId>,
        possessive_transition_controls: PackedRows<PossessiveTransitionControl>,
        start_state: AutomatonStateId,
        source_payload_floor_bytes: usize,
    ) -> Self {
        Self {
            states: states.into_boxed_slice(),
            symbol_slot_count,
            transitions,
            epsilon_transitions,
            unconditional_dispatch,
            possessive_transition_controls,
            start_state,
            source_payload_floor_bytes,
        }
    }

    #[inline]
    fn transition_row(
        &self,
        id: AutomatonStateId,
        symbol_index: usize,
    ) -> &[AutomatonStateId] {
        let row = id.index() * self.symbol_slot_count + symbol_index;
        self.transitions.row(row)
    }

    /// Explicit entry state for this automaton.
    #[inline]
    pub const fn start_state(&self) -> AutomatonStateId {
        self.start_state
    }

    /// Resolve a checked state ID from a dense runtime index.
    #[inline]
    pub fn state_id(&self, index: usize) -> Option<AutomatonStateId> {
        AutomatonStateId::try_new(index, self.states.len())
    }

    /// Iterate over borrowed state views in state-ID order.
    #[inline]
    pub fn states(
        &self,
    ) -> impl ExactSizeIterator<Item = CompiledStateRef<'_>> + Clone + '_ {
        self.states.iter().enumerate().map(|(index, descriptor)| {
            let id = AutomatonStateId::from_validated(index, self.states.len());
            CompiledStateRef {
                nfa: self,
                id,
                descriptor,
            }
        })
    }

    /// Resolve one state from an ID issued by this automaton's sealed domain.
    #[inline]
    pub fn state(&self, id: AutomatonStateId) -> CompiledStateRef<'_> {
        CompiledStateRef {
            nfa: self,
            id,
            descriptor: &self.states[id.index()],
        }
    }

    /// Fallible lookup for IDs retained by runtime state.
    #[inline]
    pub fn get_state(&self, id: AutomatonStateId) -> Option<CompiledStateRef<'_>> {
        self.states
            .get(id.index())
            .map(|descriptor| CompiledStateRef {
                nfa: self,
                id,
                descriptor,
            })
    }

    /// Number of states in the sealed arena.
    #[inline]
    pub fn state_count(&self) -> usize {
        self.states.len()
    }

    /// Retained graph allocation bytes, excluding this inline owner.
    pub(crate) fn retained_heap_bytes(&self) -> Option<usize> {
        fn packed_bytes<T>(rows: &PackedRows<T>) -> Option<usize> {
            size_of_val(rows.offsets.as_ref())
                .checked_add(size_of_val(rows.values.as_ref()))
        }
        size_of_val(self.states.as_ref())
            .checked_add(packed_bytes(&self.transitions)?)?
            .checked_add(packed_bytes(&self.epsilon_transitions)?)?
            .checked_add(packed_bytes(&self.unconditional_dispatch)?)?
            .checked_add(packed_bytes(&self.possessive_transition_controls)?)
    }

    /// Stable source-payload floor used by lane-program capacity admission.
    #[inline]
    pub const fn source_payload_floor_bytes(&self) -> usize {
        self.source_payload_floor_bytes
    }
}

/// Zero-width anchor predicates attached to epsilon transitions.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum AnchorPredicate {
    /// Require the start-of-input position.
    StartOfInput,
    /// Require the end-of-input position.
    EndOfInput,
}