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.

use crate::execution::matching::graph::fallible_vec::{filled, reserved};
use crate::execution::matching::graph::ordered_transitions::OrderedTransitionTable;
use crate::nfa::CompiledAutomaton;
use datafusion::common::{DataFusionError, Result};

use super::LaneRejection;

pub(crate) struct GraphLayout {
    pub(crate) cycle_positions: Vec<u64>,
    pub(crate) cycle_words: Vec<Box<[u32]>>,
    /// Static frontiers merge by graph state; payload-distinct lanes use a runtime limit.
    pub(crate) static_live_lanes: usize,
    /// Whether any reachable state can retain more than one successor per row.
    pub(crate) can_fork: bool,
    pub(crate) path_runs_per_lane: usize,
}

pub(crate) type GraphOutcome = std::result::Result<GraphLayout, LaneRejection>;

fn malformed(message: impl Into<String>) -> DataFusionError {
    DataFusionError::Internal(message.into())
}

macro_rules! bounded {
    ($value:expr) => {
        match $value {
            Some(value) => value,
            None => return Ok(Err(LaneRejection::Capacity)),
        }
    };
}

pub(crate) fn analyze_graph(
    compiled: &CompiledAutomaton,
    transitions: &OrderedTransitionTable,
) -> Result<GraphOutcome> {
    let state_count = compiled.nfa().state_count();
    let mut reachable = filled(state_count, false, "reachability entries")?;
    let mut reverse_counts = filled(state_count, 0usize, "reverse-edge counts")?;
    let mut finish = reserved(state_count, "lane finish-order entries")?;
    let mut dfs = reserved(state_count, "lane DFS frames")?;
    let start = compiled.nfa().start_state().index();
    reachable[start] = true;
    dfs.push((start, 0usize));
    while let Some(&(state, offset)) = dfs.last() {
        let state_id = compiled
            .nfa()
            .state_id(state)
            .expect("lane graph slot belongs to the sealed NFA");
        let range = transitions.sealed_range(state_id);
        let edge_id = range.start.checked_add(offset).ok_or_else(|| {
            malformed("MATCH_RECOGNIZE lane DFS transition offset overflow")
        })?;
        if edge_id < range.end {
            dfs.last_mut().expect("DFS frame exists").1 += 1;
            let target = transitions.sealed_edge(edge_id).next_state_id.index();
            reverse_counts[target] = bounded!(reverse_counts[target].checked_add(1));
            if !reachable[target] {
                reachable[target] = true;
                dfs.push((target, 0));
            }
        } else {
            dfs.pop();
            finish.push(state);
        }
    }

    // Pack predecessor rows together so construction and retirement need no
    // separate allocation per state. Counts become private write cursors.
    let mut reverse_offsets =
        reserved(bounded!(state_count.checked_add(1)), "reverse-edge offsets")?;
    let mut reverse_edge_count = 0usize;
    for count in &mut reverse_counts {
        let start = reverse_edge_count;
        reverse_edge_count = bounded!(reverse_edge_count.checked_add(*count));
        reverse_offsets.push(start);
        *count = start;
    }
    reverse_offsets.push(reverse_edge_count);
    let mut reverse_edges = filled(reverse_edge_count, 0usize, "reverse edges")?;
    for &source in &finish {
        let source_id = compiled
            .nfa()
            .state_id(source)
            .expect("lane graph slot belongs to the sealed NFA");
        for edge in transitions.sealed_edges_for_state(source_id) {
            let target = edge.next_state_id.index();
            reverse_edges[reverse_counts[target]] = source;
            reverse_counts[target] += 1;
        }
    }
    drop(reverse_counts);

    let mut component = filled(state_count, usize::MAX, "component IDs")?;
    let mut components = reserved(state_count, "lane component bounds")?;
    let mut stack = reserved(state_count, "lane reverse DFS states")?;
    for &start in finish.iter().rev() {
        if component[start] != usize::MAX {
            continue;
        }
        let id = components.len();
        let mut size = 0usize;
        let mut minimum = start;
        stack.push(start);
        component[start] = id;
        while let Some(state) = stack.pop() {
            size = size.checked_add(1).ok_or_else(|| {
                malformed("MATCH_RECOGNIZE lane component size overflow")
            })?;
            minimum = minimum.min(state);
            for &predecessor in
                &reverse_edges[reverse_offsets[state]..reverse_offsets[state + 1]]
            {
                if component[predecessor] == usize::MAX {
                    component[predecessor] = id;
                    stack.push(predecessor);
                }
            }
        }
        components.push((size, minimum));
    }
    let component_count = components.len();
    let mut cyclic = filled(component_count, false, "cycle flags")?;
    for &source in &finish {
        let source_component = component[source];
        let mut internal_edges = 0usize;
        let source_id = compiled
            .nfa()
            .state_id(source)
            .expect("lane graph slot belongs to the sealed NFA");
        for edge in transitions.sealed_edges_for_state(source_id) {
            let target = edge.next_state_id.index();
            let target_component = component[target];
            if source_component == target_component {
                internal_edges = bounded!(internal_edges.checked_add(1));
            } else if source_component >= target_component {
                return Err(malformed(
                    "MATCH_RECOGNIZE lane component order contradicts a consuming edge",
                ));
            }
        }
        let source_is_cyclic = components[source_component].0 > 1 || internal_edges != 0;
        if source_is_cyclic && internal_edges != 1 {
            return Ok(Err(LaneRejection::Graph));
        }
        cyclic[source_component] |= source_is_cyclic;
    }

    let mut cycle_positions = filled(state_count, u64::MAX, "state cycle positions")?;
    let cycle_count = cyclic.iter().filter(|&&value| value).count();
    let mut cycle_words = reserved(cycle_count, "lane cycle words")?;
    for id in 0..component_count {
        if !cyclic[id] {
            continue;
        }
        let cycle_id = bounded!(
            u32::try_from(cycle_words.len())
                .ok()
                .filter(|&value| value != u32::MAX)
        );
        bounded!(u32::try_from(components[id].0).ok());
        let mut word = reserved(components[id].0, "lane cycle edges")?;
        let start = components[id].1;
        let mut state = start;
        for phase in 0..components[id].0 {
            if cycle_positions[state] != u64::MAX {
                return Err(malformed(
                    "MATCH_RECOGNIZE lane cycle revisits a state early",
                ));
            }
            let phase = bounded!(u32::try_from(phase).ok());
            cycle_positions[state] = u64::from(cycle_id) << 32 | u64::from(phase);
            let state_id = compiled
                .nfa()
                .state_id(state)
                .expect("lane graph slot belongs to the sealed NFA");
            let mut internal_edge = None;
            for edge_id in transitions.sealed_range(state_id) {
                if component[transitions.sealed_edge(edge_id).next_state_id.index()] == id
                {
                    internal_edge = Some(edge_id);
                }
                if internal_edge.is_some() {
                    break;
                }
            }
            let edge_id = internal_edge.expect("cyclic state has one internal edge");
            word.push(bounded!(u32::try_from(edge_id).ok()));
            state = transitions.sealed_edge(edge_id).next_state_id.index();
        }
        if state != start {
            return Err(malformed(
                "MATCH_RECOGNIZE lane cycle does not close at its canonical state",
            ));
        }
        cycle_words.push(word.into_boxed_slice());
    }

    // Each simple cycle contributes at most one compressed run. Between cycles,
    // histories follow the component DAG, so this structural bound does not
    // depend on how many distinct aggregate payloads reach a graph state.
    let mut suffix_runs = filled(component_count, 0usize, "lane path-run bounds")?;
    let mut static_live_lanes = 0usize;
    let mut can_fork = false;
    for &source in &finish {
        let id = component[source];
        let cycle_run = usize::from(cyclic[id]);
        suffix_runs[id] = suffix_runs[id].max(cycle_run);
        let source_id = compiled
            .nfa()
            .state_id(source)
            .expect("lane graph slot belongs to the sealed NFA");
        let range = transitions.sealed_range(source_id);
        static_live_lanes =
            bounded!(static_live_lanes.checked_add(usize::from(!range.is_empty())));
        let mut has_continuing_edge = false;
        for edge in transitions.sealed_edges_for_state(source_id) {
            // Terminal acceptances use scratch/incumbent storage, not a bank slot.
            if !transitions.sealed_range(edge.next_state_id).is_empty() {
                can_fork |= has_continuing_edge;
                has_continuing_edge = true;
            }
            let target = component[edge.next_state_id.index()];
            if target != id {
                let runs = bounded!(
                    suffix_runs[target]
                        .checked_add(1)
                        .and_then(|n| n.checked_add(cycle_run))
                );
                suffix_runs[id] = suffix_runs[id].max(runs);
            }
        }
    }
    // The initial root needs a bank slot even in a structurally pruned graph.
    static_live_lanes = static_live_lanes.max(1);

    if can_fork && cycle_words.is_empty() {
        // Acyclic frontiers whose states have unique consuming depths need
        // only the widest depth. Terminal joins never occupy a continuing bank.
        // Otherwise static equivalence still bounds the frontier by state count.
        let mut depths = filled(state_count, usize::MAX, "lane state depths")?;
        let mut counts = filled(finish.len(), 0usize, "lane depth widths")?;
        depths[start] = 0;
        let mut peak = 1;
        let mut uniform = true;
        for &source in finish.iter().rev() {
            let source_id = compiled
                .nfa()
                .state_id(source)
                .expect("lane graph slot belongs to the sealed NFA");
            if !transitions.sealed_range(source_id).is_empty() {
                let count = &mut counts[depths[source]];
                *count = bounded!(count.checked_add(1));
                peak = peak.max(*count);
            }
            for edge in transitions.sealed_edges_for_state(source_id) {
                if !transitions.sealed_range(edge.next_state_id).is_empty() {
                    let depth = bounded!(depths[source].checked_add(1));
                    let target = &mut depths[edge.next_state_id.index()];
                    if *target == usize::MAX {
                        *target = depth;
                    } else if *target != depth {
                        uniform = false;
                        break;
                    }
                }
            }
            if !uniform {
                break;
            }
        }
        if uniform {
            static_live_lanes = peak;
        }
    }

    let path_runs_per_lane = suffix_runs[component[start]].max(1);
    let path_runs_per_lane = compiled
        .max_match_rows()
        .map_or(path_runs_per_lane, |rows| path_runs_per_lane.min(rows));
    bounded!(u32::try_from(path_runs_per_lane).ok());
    Ok(Ok(GraphLayout {
        cycle_positions,
        cycle_words,
        static_live_lanes,
        can_fork,
        path_runs_per_lane,
    }))
}