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.

//! Tentative, typed candidate effects for a single eligible edge. The cursor
//! owns the source frame until its edge decision and every sibling probe finish.
use super::LaneScanProgram;
use crate::config::YieldPolicy;
use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::matching::row_loop::{types::NavigationReadView, vm_executor};
use crate::execution::matching::{
    ExecutableIncrementalEvaluator, ExecutablePatternVariant, ExecutableSymbolEvaluator,
    ExecutableUserSymbolProgram, PatternMatcher,
};
use crate::execution::storage::bound_columns::BoundBatchRow;
use datafusion::common::Result;

#[inline]
pub(crate) fn direct_quantum(yield_policy: YieldPolicy) -> usize {
    match yield_policy {
        #[cfg(test)]
        YieldPolicy::TestBudget(n) => n.get().min(COARSE_WORK_BATCH_SIZE),
        _ => COARSE_WORK_BATCH_SIZE,
    }
}

#[derive(Default)]
pub(crate) struct DirectRouteCounters {
    pub(crate) lane_started: usize,
    pub(crate) used_bound_input: bool,
    pub(crate) direct: usize,
    continuous: usize,
    inline_lane: usize,
    winners: usize,
    winning_registers: usize,
}

impl DirectRouteCounters {
    #[inline]
    pub(crate) fn record_winning_registers(&mut self, count: usize) {
        self.winning_registers += count;
    }

    #[inline]
    pub(crate) fn record_continuous(
        &mut self,
        winner: bool,
        advanced: bool,
        bound: bool,
    ) {
        self.used_bound_input |= bound;
        self.continuous += 1;
        self.direct += usize::from(advanced);
        self.winners += usize::from(winner);
    }

    #[inline]
    pub(crate) fn record_inline_lane(&mut self, winner: bool, bound: bool) {
        self.used_bound_input |= bound;
        self.inline_lane += 1;
        self.winners += usize::from(winner);
    }

    #[inline]
    pub(crate) fn merge(&mut self, other: &Self) {
        self.used_bound_input |= other.used_bound_input;
        self.direct += other.direct;
        self.lane_started += other.lane_started;
        self.continuous += other.continuous;
        self.inline_lane += other.inline_lane;
        self.winners += other.winners;
        self.winning_registers += other.winning_registers;
    }

    pub(crate) fn record_routes(
        &self,
        matcher: &PatternMatcher,
        variant: &ExecutablePatternVariant,
    ) {
        if let Some(metrics) = &matcher.services.metrics {
            if self.used_bound_input {
                metrics.route_scan_bound_input.add(1);
            }
            if self.continuous != 0 {
                metrics.route_scan_continuous.add(self.continuous);
            }
            if self.winners != 0 {
                metrics.output_compact_matches.add(self.winners);
            }
            if self.winning_registers != 0 {
                metrics
                    .output_winning_register_values
                    .add(self.winning_registers);
            }
            let started = self.lane_started + self.continuous + self.inline_lane;
            if started != 0 {
                metrics.route_scan_specialized.add(started);
                metrics.route_path_compact.add(started);
                variant
                    .symbol_execution_plan()
                    .record_evaluator_routes(metrics, false, started);
            }
            if self.direct != 0 {
                metrics.route_scan_direct_linear.add(self.direct);
            }
        }
    }
}

#[derive(Clone, Copy)]
pub(crate) struct DirectRow<'a> {
    pub(crate) current: Option<BoundBatchRow<'a>>,
    pub(crate) candidate_start: Option<BoundBatchRow<'a>>,
    pub(crate) sequence: i64,
    pub(crate) match_number: u64,
}

/// Worst-case logical work for this symbol. Only a compiled typed evaluator
/// can run directly on bound inputs without constructing scalar state.
pub(crate) fn direct_payload_work(user: &ExecutableUserSymbolProgram) -> Option<usize> {
    if user.accumulation_program().has_retained_row_updates() {
        return None;
    }
    let predicate = match user.evaluator() {
        ExecutableSymbolEvaluator::Static => 0,
        ExecutableSymbolEvaluator::Incremental(
            ExecutableIncrementalEvaluator::Direct { predicate, .. },
        ) => predicate.direct_loop_work()?,
        _ => return None,
    };
    Some(
        1 + predicate
            + 3 * user.accumulation_program().ops().len()
            + user.navigation_program().ops().len(),
    )
}

/// Apply register updates, then navigation stores, then DEFINE, in the same
/// order as regular Lane. `None` requests that Lane retry the row starting
/// with its unchanged source frame, including any reached arithmetic error.
pub(crate) fn evaluate_direct_payload<const NO_NULLS: bool>(
    program: &LaneScanProgram,
    user: &ExecutableUserSymbolProgram,
    row: DirectRow<'_>,
    or_passes: bool,
    registers: &mut [u64],
    navigation: &mut [u64],
) -> Result<Option<bool>> {
    if !user.accumulation_program().ops().is_empty()
        && vm_executor::apply_direct_updates::<NO_NULLS>(
            row.current,
            registers,
            user.accumulation_program().ops(),
        )
        .is_none()
    {
        return Ok(None);
    }
    let stores = user.navigation_program().resolved();
    if !stores.is_empty() {
        let Some(layout) = program.navigation_layout.as_deref() else {
            return Ok(None);
        };
        // Validate the frame once. Bound stores use only direct word offsets.
        layout.view(navigation)?;
        let mut cached = None;
        for store in stores {
            let key = (store.domain, store.column);
            let (words, is_null) =
                if let Some((_, value)) = cached.filter(|(last, _)| *last == key) {
                    value
                } else {
                    use crate::core::vm::NavigationValueDomain;
                    let value = if let Some(column) = store.column {
                        let Some(row) = row.current else {
                            return Ok(None);
                        };
                        let value = match store.domain {
                            NavigationValueDomain::Primitive => row
                                .read_word_checked(column, false)
                                .map(|v| v.map(|word| [word, 0])),
                            NavigationValueDomain::Decimal128 => row
                                .read_decimal_checked(column)
                                .map(|v| v.map(|raw| [raw as u64, (raw >> 64) as u64])),
                            NavigationValueDomain::Classifier => unreachable!(),
                        };
                        let Some(value) = value else {
                            return Ok(None);
                        };
                        (value.unwrap_or([0; 2]), value.is_none())
                    } else {
                        ([user.id().index() as u64, 0], false)
                    };
                    cached = Some((key, value));
                    value
                };
            store.target.apply(navigation, words, is_null);
        }
    }
    if or_passes {
        return Ok(Some(true));
    }
    let value = match user.evaluator() {
        ExecutableSymbolEvaluator::Static => Some(true),
        ExecutableSymbolEvaluator::Incremental(
            ExecutableIncrementalEvaluator::Direct { predicate, .. },
        ) => {
            let nav = if let Some(layout) = program.navigation_layout.as_deref() {
                NavigationReadView::Packed(layout.view(navigation)?)
            } else {
                NavigationReadView::Empty
            };
            predicate.evaluate_direct_row(row, registers, nav)
        }
        _ => None,
    };
    Ok(value)
}