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.

//! Core NFA transition logic.

use super::policies::AnchorPolicy;
use super::scan::transition::{TransitionDisposition, TransitionSource, TransitionStep};
use super::state::WorkGovernor;
use super::state::{AcceptingCandidate, BestMatch};
use super::types::ActiveThread;
use crate::core::{AbsoluteRow, PhysicalRowCount, SymbolId};
use crate::execution::common::coordinates::{
    absolute_row_from_usize, absolute_row_to_usize,
};
use crate::execution::matching::PatternMatcher;
use crate::execution::matching::dedup::DedupArena;
use crate::execution::matching::graph::path_nodes::PathNodeArena;
use crate::execution::matching::path::{
    PathRepresentation, PathStep, Sym, compact_path_node,
};
use crate::execution::matching::state_set::{PathEquivalenceCheck, StateInsertion};
use crate::nfa::{AnchorEnvironment, AutomatonStateId, CompiledAutomaton};
use datafusion::common::Result;

pub(super) struct TransitionKernel<'a> {
    pub(super) compiled: &'a CompiledAutomaton,
    pub(super) path_representation: &'a PathRepresentation,
    pub(super) node_arena: &'a mut PathNodeArena,
    pub(super) incumbent: &'a mut Option<AcceptingCandidate>,
}

/// Immutable transition-finalization inputs for one accepted edge.
pub(super) struct FinalizeTransitionRequest {
    pub(super) nfa_state_id: AutomatonStateId,
    pub(super) sym_id: SymbolId,
    pub(super) next_state_id: AutomatonStateId,
    /// Evaluate a history-dependent predicate before publishing this edge.
    pub(super) needs_history: bool,
    pub(super) current_row: usize,
    pub(super) partition_start_row: usize,
    pub(super) partition_len: usize,
    pub(super) global_row_offset: usize,
    pub(super) current_match_number: u64,
    pub(super) source: TransitionSource,
    pub(super) disposition: TransitionDisposition,
}

#[derive(Clone, Copy)]
pub(crate) struct TransitionCompletion {
    pub(crate) disposition: TransitionDisposition,
    pub(crate) accepted: bool,
    pub(crate) retires_row: bool,
}

impl TransitionCompletion {
    pub(crate) fn step(self) -> TransitionStep {
        if !self.accepted {
            TransitionStep::Skipped
        } else if self.retires_row {
            TransitionStep::RowComplete
        } else if self.disposition == TransitionDisposition::ConsumeSource {
            TransitionStep::SourceComplete
        } else {
            TransitionStep::Finalized
        }
    }
}

pub(super) struct PendingHistory {
    pub(super) symbol: SymbolId,
    pub(super) match_number: u64,
    pub(super) started: bool,
}

struct TransitionRollback {
    node_arena_len: usize,
    previous_incumbent: Option<AcceptingCandidate>,
}

enum FinalizationPhase {
    Commit {
        accepting: Option<AcceptingCandidate>,
        retain_in_next: bool,
    },
    VerifyingHistory(PathEquivalenceCheck),
}

/// One evaluated successor and all progress needed before it is published.
pub(crate) struct PendingTransition {
    pub(crate) candidate: Option<ActiveThread>,
    pub(crate) source: TransitionSource,
    pub(crate) active_idx: usize,
    pub(crate) completion: TransitionCompletion,
    pub(super) history: Option<PendingHistory>,
    rollback: TransitionRollback,
    phase: FinalizationPhase,
}

impl PendingTransition {
    pub(super) fn abort(
        mut self,
        node_arena: &mut PathNodeArena,
        incumbent: &mut Option<AcceptingCandidate>,
    ) -> ActiveThread {
        *incumbent = self.rollback.previous_incumbent;
        node_arena.truncate(self.rollback.node_arena_len);
        self.candidate
            .take()
            .expect("failed transition retains its successor")
    }
}

#[inline]
pub(super) fn absolute_transition_row(
    current_row: usize,
    partition_start_row: usize,
    partition_len: usize,
    global_row_offset: usize,
) -> Result<AbsoluteRow> {
    let provider_row = current_row.min(partition_len);
    let provider_row = absolute_row_from_usize(provider_row, "provider row")?.as_u64();
    let partition_start_row =
        absolute_row_from_usize(partition_start_row, "partition start")?.as_u64();
    let global_row_offset =
        absolute_row_from_usize(global_row_offset, "global row offset")?.as_u64();
    provider_row
        .checked_add(partition_start_row)
        .and_then(|row| row.checked_add(global_row_offset))
        .map(AbsoluteRow::new)
        .ok_or_else(|| {
            datafusion::common::DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE absolute row addition overflow".to_string(),
            )
        })
}

impl<'a> TransitionKernel<'a> {
    #[allow(
        clippy::too_many_arguments,
        reason = "generic transition leaf exposes arena and active-state borrows explicitly"
    )]
    pub(super) fn begin_transition<P: AnchorPolicy>(
        &mut self,
        matcher: &PatternMatcher,
        next_augmented_state: ActiveThread,
        request: FinalizeTransitionRequest,
        anchor_policy: &mut P,
    ) -> std::result::Result<
        PendingTransition,
        Box<(datafusion::common::DataFusionError, ActiveThread)>,
    > {
        let mut next_augmented_state = next_augmented_state;
        log::trace!(
            target: "datafusion_match_recognize::execution::matching::transition",
            event = "finalize_transition",
            current_row = request.current_row,
            from_state_id = request.nfa_state_id.index(),
            symbol_id:% = request.sym_id,
            to_state_id = request.next_state_id.index(),
            match_start_row:% = request.source.match_start_row;
            "row {}: from_state={} -> symbol_id={} -> state={}, match_start={}",
            request.current_row,
            request.nfa_state_id,
            request.sym_id,
            request.next_state_id,
            request.source.match_start_row
        );

        #[cfg(test)]
        if let Some(metrics) = &matcher.services.metrics {
            metrics.accepted_edges.add(1);
        }
        let rollback = TransitionRollback {
            node_arena_len: self.node_arena.len(),
            previous_incumbent: *self.incumbent,
        };
        let finalization = (|| -> Result<(Option<AcceptingCandidate>, bool)> {
            let absolute_row = absolute_transition_row(
                request.current_row,
                request.partition_start_row,
                request.partition_len,
                request.global_row_offset,
            )?;

            let candidate_node_idx = self.build_next_path_state(
                matcher,
                &mut next_augmented_state,
                &request,
                absolute_row,
            )?;
            // Consumption decides in the current row's environment; stopping
            // decides at the following boundary. Keep the live policy on the
            // consumed row so other transitions from this source see it too.
            let mut accepting_policy = *anchor_policy;
            let acceptance_row = absolute_row
                .checked_add(PhysicalRowCount::new(1))
                .ok_or_else(|| {
                    datafusion::common::DataFusionError::ResourcesExhausted(
                        "MATCH_RECOGNIZE acceptance position exceeds u64".into(),
                    )
                })?;
            if self.compiled.has_anchors() {
                accepting_policy.update_row(absolute_row_to_usize(
                    acceptance_row,
                    "acceptance position",
                )?);
            }
            let accept_env = accepting_policy.anchor_environment();
            if let Some(accepting_rank) = self
                .compiled
                .accepting_preference_rank(request.next_state_id, accept_env)
            {
                let candidate = AcceptingCandidate {
                    best_match: BestMatch {
                        path_end: candidate_node_idx,
                        state_id: request.next_state_id,
                        row: acceptance_row,
                        match_start_row: request.source.match_start_row,
                    },
                    end_row: absolute_row,
                };
                // Only retain this state for the next row if higher-priority
                // consuming edges exist ahead of stopping (`accepting_rank > 0`)
                // and physical rows can still follow (`!= VirtualEnd`).
                let retain_in_next = accepting_rank > 0
                    && accept_env != Some(AnchorEnvironment::VirtualEnd);
                return Ok((Some(candidate), retain_in_next));
            }
            Ok((None, true))
        })();
        let (accepting, retain_in_next) = match finalization {
            Ok(outcome) => outcome,
            Err(error) => {
                self.node_arena.truncate(rollback.node_arena_len);
                return Err(Box::new((error, next_augmented_state)));
            }
        };
        let retires_row = accepting.is_some();
        Ok(PendingTransition {
            candidate: Some(next_augmented_state),
            source: request.source,
            active_idx: 0,
            completion: TransitionCompletion {
                disposition: request.disposition,
                accepted: true,
                retires_row,
            },
            history: request.needs_history.then_some(PendingHistory {
                symbol: request.sym_id,
                match_number: request.current_match_number,
                started: false,
            }),
            rollback,
            phase: FinalizationPhase::Commit {
                accepting,
                retain_in_next,
            },
        })
    }

    pub(super) fn advance_transition(
        &mut self,
        matcher: &PatternMatcher,
        pending: &mut PendingTransition,
        arena: &mut DedupArena<'_>,
        governor: &mut WorkGovernor,
    ) -> Result<bool> {
        loop {
            match &mut pending.phase {
                FinalizationPhase::Commit {
                    accepting,
                    retain_in_next,
                } => {
                    // Priority-ordered traversal guarantees every live thread and
                    // edge before `accept_offset` strictly outranks any earlier
                    // incumbent, so an accepting transition wins unconditionally.
                    if let Some(candidate) = *accepting {
                        *self.incumbent = Some(candidate);
                    }
                    if *retain_in_next {
                        match matcher.insert_or_update_next_state(
                            self.compiled,
                            &mut pending.candidate,
                            arena,
                            governor,
                        )? {
                            StateInsertion::VerifyingHistory(check) => {
                                pending.phase =
                                    FinalizationPhase::VerifyingHistory(check);
                                continue;
                            }
                            StateInsertion::Complete => {}
                        }
                    }
                }
                FinalizationPhase::VerifyingHistory(check) => {
                    if !matcher.advance_history_equivalence(
                        self.compiled,
                        &mut pending.candidate,
                        check,
                        arena,
                        self.node_arena,
                        governor,
                    )? {
                        return Ok(false);
                    }
                }
            }
            pending.candidate = None;
            return Ok(true);
        }
    }

    #[cfg(test)]
    #[allow(clippy::too_many_arguments)]
    pub(super) fn finalize_transition<P: AnchorPolicy>(
        &mut self,
        matcher: &PatternMatcher,
        next: ActiveThread,
        request: FinalizeTransitionRequest,
        anchor_policy: &mut P,
        arena: &mut DedupArena<'_>,
        governor: &mut WorkGovernor,
    ) -> std::result::Result<(), Box<(datafusion::common::DataFusionError, ActiveThread)>>
    {
        let mut pending = self.begin_transition(matcher, next, request, anchor_policy)?;
        loop {
            match self.advance_transition(matcher, &mut pending, arena, governor) {
                Ok(true) => return Ok(()),
                Ok(false) => {}
                Err(error) => {
                    return Err(Box::new((
                        error,
                        pending.abort(self.node_arena, self.incumbent),
                    )));
                }
            }
        }
    }

    fn build_next_path_state(
        &mut self,
        matcher: &PatternMatcher,
        next_augmented_state: &mut ActiveThread,
        request: &FinalizeTransitionRequest,
        absolute_row: AbsoluteRow,
    ) -> Result<u32> {
        // Output can reconstruct the contiguous steps from the sealed shape
        // and match bounds, so a compact path needs no arena node.
        if self.path_representation.uses_compact_paths() {
            next_augmented_state.set_path(None);
            next_augmented_state.set_state_id(request.next_state_id);
            return Ok(compact_path_node());
        }

        let new_step = PathStep {
            row: absolute_row,
            sym: Sym::from_index(request.sym_id.index()),
            excluded: self
                .compiled
                .nfa()
                .state(request.nfa_state_id)
                .is_excluded(),
        };

        let new_node_idx = self.node_arena.allocate(new_step, request.source.path)?;
        next_augmented_state
            .inner_mut()
            .deferred_history_fingerprint = matcher
            .program
            .deferred_history()
            .append_fingerprint(request.source.deferred_history_fingerprint, &new_step);
        next_augmented_state.set_path(Some(new_node_idx));
        next_augmented_state.set_state_id(request.next_state_id);
        Ok(new_node_idx)
    }
}

#[cfg(test)]
mod tests {
    use super::absolute_transition_row;
    use crate::core::AbsoluteRow;

    #[test]
    fn absolute_row_preserves_late_origin() {
        let late_origin = usize::try_from(u32::MAX).unwrap();
        let row = absolute_transition_row(2, 5, 10, late_origin).unwrap();
        assert_eq!(row, AbsoluteRow::new(u64::from(u32::MAX) + 7));
    }
}