datafusion-match-recognize 0.56.0

MATCH_RECOGNIZE extension for 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.

//! Cooperative work and retained-memory accounting for partition keys.

use datafusion::arrow::array::Array;
use datafusion_common::utils::memory::RecordBatchMemoryCounter;
use datafusion_common::{DataFusionError, Result};

use crate::execution::common::progress::COARSE_WORK_BATCH_SIZE;
use crate::execution::common::scheduling::SliceControl;
use crate::execution::common::work::WorkGovernor;

/// Records bounded buffer-preparation work directly against the stream's
/// governor and yields cooperatively at batch/native boundaries.
pub(super) struct CoopWork<'a, F> {
    governor: &'a mut WorkGovernor,
    slice: &'a SliceControl,
    is_aborted: F,
    pending: usize,
}

impl<'a, F: Fn() -> bool> CoopWork<'a, F> {
    pub(super) fn new(
        governor: &'a mut WorkGovernor,
        slice: &'a SliceControl,
        is_aborted: F,
    ) -> Self {
        Self {
            governor,
            slice,
            is_aborted,
            pending: 0,
        }
    }

    pub(super) async fn complete_one(&mut self) -> Result<()> {
        self.pending += 1;
        if self.pending >= COARSE_WORK_BATCH_SIZE {
            self.flush().await?;
        }
        Ok(())
    }

    pub(super) async fn native_completed(&mut self, units: usize) -> Result<()> {
        self.pending = self
            .pending
            .checked_add(units.max(1))
            .ok_or_else(overflow)?;
        self.flush().await
    }

    pub(super) async fn flush(&mut self) -> Result<()> {
        let units = std::mem::take(&mut self.pending);
        if units != 0 {
            self.governor.record_completed(units, &self.is_aborted)?;
        }
        if self.governor.take_yield_if_due(self.slice.current_policy()) {
            self.slice.yield_once().await;
        }
        Ok(())
    }

    pub(super) fn record_sync(&mut self, units: usize) -> Result<()> {
        let total = std::mem::take(&mut self.pending).saturating_add(units);
        if total != 0 {
            self.governor.record_completed(total, &self.is_aborted)?;
        }
        Ok(())
    }
}

pub(super) fn count_array_bytes(
    counter: &mut RecordBatchMemoryCounter,
    array: &dyn Array,
) -> Result<usize> {
    let object_bytes = array
        .get_array_memory_size()
        .saturating_sub(array.get_buffer_memory_size());
    counter
        .count_array(array)
        .checked_add(object_bytes)
        .ok_or_else(overflow)
}

pub(super) fn vector_bytes<T>(values: &Vec<T>) -> Result<usize> {
    values
        .capacity()
        .checked_mul(size_of::<T>())
        .ok_or_else(overflow)
}

pub(super) fn overflow() -> DataFusionError {
    DataFusionError::ResourcesExhausted(
        "MATCH_RECOGNIZE replay-key memory size exceeds usize".into(),
    )
}