datafusion-match-recognize 0.55.0

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.

//! Inline multi-lane resolution when the direct linear cursor hits an ambiguous
//! fork within a single physical Arrow batch.

use super::batch_loop::row_masks;
use super::{BoolColKind, ClosedDirectDriver};
use crate::core::AbsoluteRow;
use crate::execution::matching::row_loop::lane_scan::{
    LaneScanState, commit_scratch_transition,
    direct_payload::{DirectRow, evaluate_direct_payload},
    is_lane_capacity_miss,
};
use crate::execution::matching::row_loop::state::WorkGovernor;
use crate::execution::storage::bound_columns::{BoundBatchColumns, BoundBatchRow};
use datafusion::arrow::array::{BooleanArray, RecordBatch};
use datafusion::common::Result;

pub(super) enum InlineLaneOutcome {
    Resolved,
    Yield,
    Handoff,
}

impl ClosedDirectDriver<'_> {
    #[expect(clippy::too_many_arguments)]
    pub(super) fn run_ambiguous_lane<const NO_NULLS: bool, const TRACK_HISTORY: bool>(
        &self,
        lane: &mut LaneScanState,
        arrow: &RecordBatch,
        row_idx: usize,
        batch_span_end: usize,
        is_eof: bool,
        batch_origin: usize,
        bound: Option<&BoundBatchColumns>,
        candidate_row: Option<BoundBatchRow<'_>>,
        packed: Option<&[u64]>,
        bool_cols: &[(&BooleanArray, u64, BoolColKind)],
        match_number: u64,
        governor: &mut WorkGovernor,
        work: &mut usize,
    ) -> Result<InlineLaneOutcome> {
        let matcher = self.matcher;
        let variant = self.variant;
        let program = self.program;
        let automaton = variant.automaton();
        let transitions = &program.transitions;
        let symbol_programs = variant.symbol_programs();
        let eager_bitmap = self.eager_bitmap;
        let quantum = self.quantum;
        let yield_policy = self.yield_policy;

        let mut row = self
            .cursor
            .seed_lane::<TRACK_HISTORY>(lane, work)
            .unwrap_or(row_idx);

        while row < batch_span_end && lane.active_len() > 0 {
            if *work >= quantum {
                governor
                    .record_completed(std::mem::take(work), || matcher.is_aborted())?;
                if governor.take_yield_if_due_hot(yield_policy) {
                    return Ok(InlineLaneOutcome::Yield);
                }
            }
            let local = row - batch_origin;
            let masks = row_masks(local, packed, bool_cols, eager_bitmap);
            let eligible = masks.eligible;
            let abs_row = AbsoluteRow::new(row as u64);
            let operands = DirectRow {
                current: bound.and_then(|b| b.row(local)),
                candidate_start: candidate_row,
                sequence: (row - row_idx + 1) as i64,
                match_number,
            };
            let active_len = lane.active_len();
            'row: for active in 0..active_len {
                if *work >= quantum {
                    governor.record_completed(std::mem::take(work), || {
                        matcher.is_aborted()
                    })?;
                    if governor.take_yield_if_due_hot(yield_policy) {
                        return Ok(InlineLaneOutcome::Yield);
                    }
                }
                let source = lane
                    .active_state(active)
                    .expect("active lane within active_len")
                    .state_id;
                let required = program.state_symbols_mask(source);
                if eligible & required == 0 {
                    *work += 1;
                    continue;
                }
                for edge_id in transitions.sealed_range(source) {
                    let edge = transitions.sealed_edge(edge_id);
                    if edge.after_accept {
                        break 'row;
                    }
                    let sym_bit = 1u64 << edge.symbol_id.index();
                    if eligible & sym_bit == 0 {
                        *work += 1;
                        continue;
                    }
                    let is_payload = program.payload_symbols & sym_bit != 0;
                    let edge_work = if is_payload {
                        usize::from(program.direct_edge_work(edge_id))
                    } else {
                        0
                    };
                    if *work != 0 && work.saturating_add(edge_work + 1) > quantum {
                        governor.record_completed(std::mem::take(work), || {
                            matcher.is_aborted()
                        })?;
                        if governor.take_yield_if_due_hot(yield_policy) {
                            return Ok(InlineLaneOutcome::Yield);
                        }
                    }
                    *work += 1;
                    let retains =
                        !transitions.sealed_range(edge.next_state_id).is_empty();
                    *work += lane.prepare_transition(active, retains)?;
                    if is_payload {
                        let user = symbol_programs[edge.symbol_id.index()]
                            .user()
                            .expect("admitted consuming edge has a user program");
                        let (regs, nav) = lane.scratch_payload_mut();
                        *work += edge_work;
                        let or_pass = masks.or_passes & sym_bit != 0;
                        let cached =
                            matcher.program.classification.as_ref().and_then(|c| {
                                c.cached_demand(arrow, local, edge.symbol_id)
                            });
                        match cached.map_or_else(
                            || {
                                evaluate_direct_payload::<NO_NULLS>(
                                    program, user, operands, or_pass, regs, nav,
                                )
                            },
                            |value| Ok(Some(value)),
                        ) {
                            Ok(Some(true)) => {}
                            Ok(Some(false)) => continue,
                            Ok(None) | Err(_) => return Ok(InlineLaneOutcome::Handoff),
                        }
                    }
                    if let Err(err) =
                        lane.apply_scratch_transition(source, edge_id, abs_row)
                    {
                        if is_lane_capacity_miss(&err) {
                            return Ok(InlineLaneOutcome::Handoff);
                        }
                        return Err(err);
                    }
                    let row_complete = match commit_scratch_transition(
                        matcher,
                        automaton,
                        lane,
                        abs_row,
                        retains,
                        true,
                        &mut |units| {
                            *work += units;
                            Ok(())
                        },
                    ) {
                        Ok(publication) => publication,
                        Err(err) if is_lane_capacity_miss(&err) => {
                            return Ok(InlineLaneOutcome::Handoff);
                        }
                        Err(err) => return Err(err),
                    };
                    if row_complete {
                        break 'row;
                    }
                }
            }
            lane.finish_row();
            *work += 1;
            row += 1;
        }
        if !is_eof && row >= batch_span_end && lane.active_len() > 0 {
            return Ok(InlineLaneOutcome::Handoff);
        }
        Ok(InlineLaneOutcome::Resolved)
    }
}