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.

use crate::core::AbsoluteRow;
use crate::execution::matching::graph::ordered_transitions::OrderedTransitionTable;
use crate::nfa::{AnchorEnvironment, AutomatonStateId};
use std::sync::Arc;

use crate::core::vm::MAX_REGISTERS;
use crate::execution::matching::row_loop::types::PackedNavigationLayout;

/// Sealed transitions, paths, registers, and navigation for Lane.
pub(crate) struct LaneScanProgram {
    pub(crate) transitions: Arc<OrderedTransitionTable>,
    pub(crate) closure_accepting: Arc<[Option<AutomatonStateId>]>,
    pub(crate) boundary_anchors: LaneBoundaryAnchors,
    pub(crate) cycle_positions: Box<[u64]>,
    pub(crate) cycles: Box<[Box<[u32]>]>,
    pub(crate) capacity: LaneCapacity,
    /// A soft capacity miss restarts the unpublished candidate through General.
    pub(crate) optimistic_history: bool,
    pub(super) initial_registers: [u64; MAX_REGISTERS],
    pub(super) register_words: usize,
    pub(super) navigation_layout: Option<Arc<PackedNavigationLayout>>,
    pub(super) navigation_words: usize,
    pub(crate) payload_symbols: u64,
    pub(super) idempotent_last_symbols: u64,
    pub(super) direct_linear: bool,
    pub(crate) suffix_reuse: Option<DirectSuffixReuse>,
    pub(super) state_meta: Box<[DirectStateMeta]>,
    pub(super) direct_edges: Box<[DirectEdge]>,
    /// Per-edge native work bound; all-static programs have zero payload work.
    pub(crate) direct_payload_work: u8,
}

/// Entry and the accepting loop share one ordered, memoryless step list.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct DirectSuffixReuse {
    pub(crate) body_mask: u64,
    pub(super) start: u32,
    pub(super) len: u16,
}

/// Both tables use the original sealed edge IDs, including duplicate labels.
#[derive(Clone, Copy)]
pub(super) struct DirectStateMeta {
    pub(super) symbols: u64,
    pub(super) start: u32,
    /// Saturates at the per-row edge limit; such states always hand off.
    pub(super) len: u16,
    pub(super) max_work: u16,
}

impl DirectStateMeta {
    #[inline]
    pub(super) fn can_step_static_packed(
        self,
        payload: u64,
        cached: u64,
        last_only: u64,
    ) -> bool {
        payload & self.symbols & !cached & !last_only == 0
    }
}

#[derive(Clone, Copy)]
pub(super) struct DirectEdge {
    pub(super) next_state: u16,
    pub(super) symbol: u8,
    pub(super) flags: u8,
    pub(super) work: u8,
}

impl DirectEdge {
    pub(super) const PAYLOAD: u8 = 1;
    pub(super) const ACCEPTING: u8 = 2;
    pub(super) const CONTINUING: u8 = 4;
    pub(super) const AFTER_ACCEPT: u8 = 8;
    pub(super) const IDEMPOTENT_LAST_ONLY: u8 = 16;
}

impl std::fmt::Debug for LaneScanProgram {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LaneScanProgram")
            .field("states", &self.closure_accepting.len())
            .field("edges", &self.transitions.edge_count())
            .field("cycles", &self.cycles.len())
            .field("navigation_words", &self.navigation_words)
            .field("capacity", &self.capacity)
            .finish()
    }
}

/// A zero count denotes an absent symbol. Its coordinates have no meaning.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub(crate) struct SymbolFacts {
    pub(crate) first: AbsoluteRow,
    pub(crate) last: AbsoluteRow,
    pub(crate) count: u64,
}

/// Fixed graph identity and compressed-history length for one lane.
#[derive(Clone, Copy)]
pub(crate) struct LaneState {
    pub(crate) state_id: AutomatonStateId,
    pub(crate) history_runs: u32,
}

/// Coarse reason that a valid executable program remains on the generic route.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LaneRejection {
    Graph,
    Evaluator,
    State,
    Path,
    Capacity,
}

impl From<crate::execution::matching::graph::reachability::ReachabilityRejection>
    for LaneRejection
{
    fn from(
        reason: crate::execution::matching::graph::reachability::ReachabilityRejection,
    ) -> Self {
        match reason {
            crate::execution::matching::graph::reachability::ReachabilityRejection::Graph => Self::Graph,
            crate::execution::matching::graph::reachability::ReachabilityRejection::Nullable => Self::Path,
            crate::execution::matching::graph::reachability::ReachabilityRejection::Capacity => Self::Capacity,
        }
    }
}

impl std::fmt::Display for LaneRejection {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let reason = match self {
            Self::Graph => "graph",
            Self::Evaluator => "evaluator",
            Self::State => "state",
            Self::Path => "path",
            Self::Capacity => "capacity",
        };
        f.write_str(reason)
    }
}

/// Storage capacities selected when compiling one candidate-scan resource.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct LaneCapacity {
    pub(crate) live_lanes: usize,
    pub(crate) path_runs_per_lane: usize,
    pub(crate) encoded_program_bytes: usize,
    pub(crate) source_payload_floor_bytes: usize,
    /// Exact retained capacity of the fixed lane, register, navigation, and
    /// history slabs. Active and successor generations, sibling scratch, and
    /// incumbent are included.
    pub(crate) scan_resource_bytes: usize,
}

/// Boundary-anchor contract proven for a compiled [`LaneScanProgram`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LaneBoundaryAnchors {
    /// Pattern contains no `^` or `$` anchors.
    None,
    /// Pattern contains anchors only at partition boundaries:
    /// - Every match must start at `partition_start` (`^` prefix),
    ///   `start_state` uses `PhysicalStart` closure and has consuming in-degree 0,
    ///   and all other states are start-anchor-invariant.
    /// - `end_anchored`: every match must end at `partition_end` (`$` suffix),
    ///   no state accepts in `PhysicalInterior`, and `closure_accepting` holds
    ///   `VirtualEnd` accepting states evaluated only on the final partition row.
    Boundary { end_anchored: bool },
}

impl LaneBoundaryAnchors {
    #[inline]
    pub(crate) const fn requires_partition_start(self) -> bool {
        matches!(self, Self::Boundary { .. })
    }

    #[inline]
    pub(crate) const fn requires_partition_end(self) -> bool {
        matches!(self, Self::Boundary { end_anchored: true })
    }

    #[inline]
    pub(crate) fn dispatch_environment(
        self,
        state_id: AutomatonStateId,
        start_state: AutomatonStateId,
    ) -> Option<AnchorEnvironment> {
        match self {
            Self::None => None,
            Self::Boundary { .. } => Some(if state_id == start_state {
                AnchorEnvironment::PhysicalStart
            } else {
                AnchorEnvironment::PhysicalInterior
            }),
        }
    }

    #[inline]
    pub(crate) const fn accept_environment(self) -> Option<AnchorEnvironment> {
        match self {
            Self::None => None,
            Self::Boundary { end_anchored: true } => Some(AnchorEnvironment::VirtualEnd),
            Self::Boundary {
                end_anchored: false,
            } => Some(AnchorEnvironment::PhysicalInterior),
        }
    }
}

/// Boundary dispatch and compressed path facts of the concrete lane program.
impl LaneScanProgram {
    #[inline]
    pub(crate) const fn requires_partition_start(&self) -> bool {
        self.boundary_anchors.requires_partition_start()
    }

    #[inline]
    pub(crate) const fn requires_partition_end(&self) -> bool {
        self.boundary_anchors.requires_partition_end()
    }

    #[inline]
    pub(crate) fn dispatch_environment(
        &self,
        state_id: AutomatonStateId,
    ) -> Option<AnchorEnvironment> {
        self.boundary_anchors
            .dispatch_environment(state_id, self.transitions.start_state())
    }

    #[inline]
    pub(crate) const fn accept_environment(&self) -> Option<AnchorEnvironment> {
        self.boundary_anchors.accept_environment()
    }
    /// Lane owner, transition table and compressed histories. Unanchored graphs
    /// alias `compiled.unconditional_first_accepting_state()`; boundary-anchored
    /// graphs own their `closure_accepting` allocation and include its exact size.
    pub(crate) fn encoded_size_bytes(
        transitions: &OrderedTransitionTable,
        boundary_anchors: LaneBoundaryAnchors,
        closure_accepting_len: usize,
        cycle_positions: &[u64],
        cycles: &[Box<[u32]>],
    ) -> Option<usize> {
        let transitions = transitions.retained_size_bytes().ok()?;
        let mut total = size_of::<Self>()
            .checked_add(2 * size_of::<usize>())
            .and_then(|n| n.checked_add(transitions))
            .and_then(|n| n.checked_add(2 * size_of::<usize>()))
            .and_then(|n| n.checked_add(size_of_val(cycle_positions)))
            .and_then(|n| n.checked_add(size_of_val(cycles)));
        if boundary_anchors.accept_environment().is_some() {
            total = total.and_then(|n| {
                closure_accepting_len
                    .checked_mul(size_of::<Option<AutomatonStateId>>())
                    .and_then(|bytes| {
                        n.checked_add(2 * size_of::<usize>())?.checked_add(bytes)
                    })
            });
        }
        for cycle in cycles {
            total = total.and_then(|n| n.checked_add(size_of_val(cycle.as_ref())));
        }
        total
    }

    pub(crate) fn cycle_position(
        &self,
        state_id: AutomatonStateId,
    ) -> Option<(u32, u32)> {
        let packed = *self.cycle_positions.get(state_id.index())?;
        (packed != u64::MAX).then_some(((packed >> 32) as u32, packed as u32))
    }
}