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.

//! Resumable matching progress and coarse runtime work reporting.

use datafusion::common::Result;

/// Outcome of one resumable compute step.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum ComputeStep {
    Complete,
    Yield,
}

/// Maximum runtime iterations completed between coarse work reports.
///
/// The work governor amortizes abort and deadline reads over its configured
/// interval. Batching here avoids a dynamic callback on every row while
/// keeping each loop's unreported tail finite.
pub(crate) const COARSE_WORK_BATCH_SIZE: usize = 64;

/// Coarse completed-work reporting for runtime loops with one callback owner.
pub(crate) struct CoarseWorkBatch<'a> {
    completed: &'a mut dyn FnMut(usize) -> Result<()>,
    counter: CoarseWorkCounter,
}

/// A callback-independent counter for loops that call cancellable helpers
/// between their own iterations.
pub(crate) struct CoarseWorkCounter {
    pending: usize,
}

impl CoarseWorkCounter {
    pub(crate) const fn new() -> Self {
        Self { pending: 0 }
    }

    #[inline]
    pub(crate) fn complete_one(
        &mut self,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<()> {
        self.pending += 1;
        if self.pending == COARSE_WORK_BATCH_SIZE {
            self.flush(completed)?;
        }
        Ok(())
    }

    pub(crate) fn finish(
        mut self,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<()> {
        self.flush(completed)
    }

    /// Flush pending work while keeping a loop error primary at the same boundary.
    pub(crate) fn finish_result<T>(
        mut self,
        result: Result<T>,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<T> {
        self.flush_result(result, completed)
    }

    /// Flush one phase boundary without consuming the shared transition counter.
    pub(crate) fn flush_result<T>(
        &mut self,
        result: Result<T>,
        completed: &mut dyn FnMut(usize) -> Result<()>,
    ) -> Result<T> {
        let accounting = self.flush(completed);
        match result {
            Err(error) => Err(error),
            Ok(value) => accounting.map(|()| value),
        }
    }

    fn flush(&mut self, completed: &mut dyn FnMut(usize) -> Result<()>) -> Result<()> {
        if self.pending == 0 {
            return Ok(());
        }
        let units = self.pending;
        self.pending = 0;
        completed(units)
    }
}

impl<'a> CoarseWorkBatch<'a> {
    pub(crate) fn new(completed: &'a mut dyn FnMut(usize) -> Result<()>) -> Self {
        Self {
            completed,
            counter: CoarseWorkCounter::new(),
        }
    }

    #[inline]
    pub(crate) fn complete_one(&mut self) -> Result<()> {
        self.counter.complete_one(self.completed)
    }

    #[inline]
    pub(crate) fn reporter(&mut self) -> &mut dyn FnMut(usize) -> Result<()> {
        &mut *self.completed
    }

    pub(crate) fn finish(self) -> Result<()> {
        self.counter.finish(self.completed)
    }

    /// Flush pending work while keeping a loop error primary at the same boundary.
    pub(crate) fn finish_result<T>(self, result: Result<T>) -> Result<T> {
        self.counter.finish_result(result, self.completed)
    }
}

#[cfg(test)]
mod tests {
    use super::CoarseWorkCounter;
    use datafusion::common::DataFusionError;

    #[test]
    fn phase_flush_keeps_operation_error_primary_and_counter_reusable() {
        let mut counter = CoarseWorkCounter::new();
        counter.complete_one(&mut |_| Ok(())).unwrap();
        let mut reported = Vec::new();
        let error = counter
            .flush_result::<()>(
                Err(DataFusionError::Execution("operation failure".into())),
                &mut |units| {
                    reported.push(units);
                    Err(DataFusionError::Execution("accounting failure".into()))
                },
            )
            .expect_err("operation failure must remain primary");
        assert!(error.to_string().contains("operation failure"), "{error}");
        assert_eq!(reported, [1]);

        counter.complete_one(&mut |_| Ok(())).unwrap();
        counter
            .finish_result(Ok(()), &mut |units| {
                reported.push(units);
                Ok(())
            })
            .unwrap();
        assert_eq!(reported, [1, 1]);
    }
}