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.

//! Borrowed selected history shared by Lane scanners and output publication.

use super::{LaneScanProgram, SymbolFacts, path::LanePathRun};
use crate::core::{AbsoluteRow, PhysicalRowCount, SymbolId};
use crate::execution::matching::ResolvedAfterMatchSkip;
use crate::execution::matching::graph::ordered_transitions::OrderedTransitionEdge;
use datafusion::common::{DataFusionError, Result};

mod captures;
pub(crate) use captures::{ClassifierDemand, SymbolCaptures};

/// The scanner remains frozen while output borrows its graph and history slab.
/// Callers retain scalar progress across suspension and reborrow this view.
pub(crate) struct LaneSelectedRuns<'a> {
    graph: &'a LaneScanProgram,
    pub(crate) runs: &'a [LanePathRun],
}

/// A winner has a checked extent. Its scanner can retain individual symbol
/// endpoints and counts, or the complete trace for row-wise classification.
pub(crate) struct CompactSelection<'a> {
    pub(crate) runs: Option<LaneSelectedRuns<'a>>,
    captures: Option<&'a SymbolCaptures>,
    pub(crate) start: AbsoluteRow,
    pub(crate) end: AbsoluteRow,
    pub(crate) acceptance: AbsoluteRow,
    pub(crate) expected_steps: PhysicalRowCount,
}

impl<'a> CompactSelection<'a> {
    /// The scanner appends only contiguous runs belonging to this graph.
    /// Verify the frozen winner against its first and last retained runs.
    pub(crate) fn try_new(
        graph: &'a LaneScanProgram,
        runs: &'a [LanePathRun],
        start: AbsoluteRow,
        end: AbsoluteRow,
        acceptance: AbsoluteRow,
    ) -> Result<Self> {
        Self::try_new_with_captures(graph, runs, None, start, end, acceptance)
    }

    /// Attach both the frozen run transcript and auxiliary O(1) symbol captures.
    pub(crate) fn try_new_with_captures(
        graph: &'a LaneScanProgram,
        runs: &'a [LanePathRun],
        captures: Option<&'a SymbolCaptures>,
        start: AbsoluteRow,
        end: AbsoluteRow,
        acceptance: AbsoluteRow,
    ) -> Result<Self> {
        let mut selection = Self::checked_extent(start, end, acceptance, captures)?;
        if runs.first().map(|run| run.first_row()) != Some(start)
            || runs
                .last()
                .and_then(|run| run.first_row().checked_add(run.steps()))
                != end.checked_add(PhysicalRowCount::new(1))
        {
            return datafusion::common::internal_err!(
                "MATCH_RECOGNIZE compact selected runs disagree with the selected extent"
            );
        }
        selection.runs = Some(LaneSelectedRuns { graph, runs });
        Ok(selection)
    }

    #[inline]
    pub(crate) fn from_extent(
        start: AbsoluteRow,
        end: AbsoluteRow,
        acceptance: AbsoluteRow,
    ) -> Result<Self> {
        Self::checked_extent(start, end, acceptance, None)
    }

    #[inline]
    pub(in crate::execution::matching) fn from_captures(
        start: AbsoluteRow,
        end: AbsoluteRow,
        acceptance: AbsoluteRow,
        captures: &'a SymbolCaptures,
    ) -> Result<Self> {
        Self::checked_extent(start, end, acceptance, Some(captures))
    }

    #[cfg(test)]
    pub(crate) fn with_captures(mut self, captures: &'a SymbolCaptures) -> Self {
        self.captures = Some(captures);
        self
    }

    #[inline]
    fn checked_extent(
        start: AbsoluteRow,
        end: AbsoluteRow,
        acceptance: AbsoluteRow,
        captures: Option<&'a SymbolCaptures>,
    ) -> Result<Self> {
        let after_end = end.as_u64().checked_add(1).ok_or_else(|| {
            DataFusionError::ResourcesExhausted(
                "MATCH_RECOGNIZE compact path end exceeds u64".into(),
            )
        })?;
        let expected_steps = after_end
            .checked_sub(start.as_u64())
            .filter(|&length| length != 0 && end <= acceptance)
            .map(PhysicalRowCount::new)
            .ok_or_else(|| {
                DataFusionError::Internal(
                    "MATCH_RECOGNIZE compact match has invalid bounds".into(),
                )
            })?;
        Ok(Self {
            start,
            end,
            acceptance,
            expected_steps,
            runs: None,
            captures,
        })
    }

    /// A requested symbol that never occurred has a zero count. A missing
    /// projection leaves the consumer free to inspect the full history.
    pub(crate) fn symbol_facts(&self, symbol: Option<SymbolId>) -> Option<SymbolFacts> {
        match symbol {
            Some(id) => self.captures?.at_winner(id),
            None => Some(SymbolFacts {
                first: self.start,
                last: self.end,
                count: self.expected_steps.as_u64(),
            }),
        }
    }

    pub(crate) fn history(&self) -> Result<&LaneSelectedRuns<'a>> {
        self.runs.as_ref().ok_or_else(|| datafusion::common::internal_datafusion_err!(
            "MATCH_RECOGNIZE selected output requires an unretained classifier history"
        ))
    }

    /// Large uncaptured words use the existing resumable selected-path replay.
    /// Bound this preflight too: each run consumes at least one unit of the limit.
    pub(crate) fn can_skip_atomically(
        &self,
        skip: &ResolvedAfterMatchSkip,
    ) -> Result<bool> {
        use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
        let symbol = match skip {
            ResolvedAfterMatchSkip::ToFirst { symbol_id, .. }
            | ResolvedAfterMatchSkip::ToLast { symbol_id, .. } => *symbol_id,
            _ => return Ok(true),
        };
        if self.symbol_facts(Some(symbol)).is_some() {
            return Ok(true);
        }
        let selected = self.history()?;
        let mut remaining = COARSE_WORK_BATCH_SIZE as u64;
        for (index, run) in selected.runs.iter().enumerate() {
            let (_, period) = selected.edge_and_period(index, 0)?;
            let Some(rest) = remaining.checked_sub(period.min(run.steps().as_u64()))
            else {
                return Ok(false);
            };
            remaining = rest;
        }
        Ok(true)
    }

    /// Resolve the restart target row for `AFTER MATCH SKIP TO FIRST/LAST`,
    /// returning `(target_row, work_units)`. `PastLastRow` and `ToNextRow`
    /// need no symbol scan and return `(None, 0)`.
    pub(crate) fn skip_target_row(
        &self,
        skip: &ResolvedAfterMatchSkip,
    ) -> Result<(Option<AbsoluteRow>, usize)> {
        let (symbol_id, last) = match skip {
            ResolvedAfterMatchSkip::PastLastRow | ResolvedAfterMatchSkip::ToNextRow => {
                return Ok((None, 0));
            }
            ResolvedAfterMatchSkip::ToFirst { symbol_id, .. } => (*symbol_id, false),
            ResolvedAfterMatchSkip::ToLast { symbol_id, .. } => (*symbol_id, true),
        };
        if let Some(facts) = self.symbol_facts(Some(symbol_id)) {
            let target =
                (facts.count != 0).then_some(if last { facts.last } else { facts.first });
            return Ok((target, 1));
        }
        let selected = self.history()?;
        let mut checked = 0usize;
        for run_position in 0..selected.runs.len() {
            let index = if last {
                selected.runs.len() - 1 - run_position
            } else {
                run_position
            };
            let run = selected.runs[index];
            let steps = run.steps().as_u64();
            let mut word_position = 0u64;
            loop {
                let offset = if last {
                    steps.checked_sub(word_position + 1).ok_or_else(|| {
                        DataFusionError::Internal(
                            "MATCH_RECOGNIZE selected lane run is empty".into(),
                        )
                    })?
                } else {
                    word_position
                };
                let (edge, period) = selected.edge_and_period(index, offset)?;
                checked += 1;
                if edge.symbol_id == symbol_id {
                    let row = run
                        .first_row()
                        .checked_add(PhysicalRowCount::new(offset))
                        .ok_or_else(|| {
                            DataFusionError::ResourcesExhausted(
                                "MATCH_RECOGNIZE skip target row exceeds u64".into(),
                            )
                        })?;
                    return Ok((Some(row), checked));
                }
                word_position += 1;
                if word_position == period.min(steps) {
                    break;
                }
            }
        }
        Ok((None, checked))
    }
}

impl<'a> LaneSelectedRuns<'a> {
    // Larger histories keep the existing resumable path replay.
    pub(crate) const MAX_ATOMIC_RUNS: usize = 64;

    pub(crate) fn edge_and_period(
        &self,
        run_index: usize,
        offset: u64,
    ) -> Result<(OrderedTransitionEdge, u64)> {
        self.run(run_index)?.edge_and_period(self.graph, offset)
    }

    fn run(&self, run_index: usize) -> Result<&LanePathRun> {
        self.runs.get(run_index).ok_or_else(|| {
            DataFusionError::Internal(
                "MATCH_RECOGNIZE selected lane run index is out of bounds".into(),
            )
        })
    }
}