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.

use std::cell::Cell;

use datafusion::common::{DataFusionError, Result, plan_err};
use prost::encoding::{DecodeContext, decode_key, skip_field};
use prost::{DecodeError, Message};

use super::payload;

// Prost keeps its default DecodeContext recursion limit private.
pub(super) const PROST_RECURSION_LIMIT: usize = 100;
pub(super) const MAX_DETAIL_BYTES: usize = 16 * 1024 * 1024;
pub(super) const MAX_SOURCE_DEPTH: usize = 256;
pub(super) const MAX_SOURCE_FIELDS: usize = 16_384;
pub(super) const MAX_SOURCE_ELEMENTS: usize = MAX_SOURCE_FIELDS;

#[derive(Clone, Copy, Default)]
struct Budget {
    depth: usize,
    fields: usize,
    elements: usize,
}

thread_local! {
    static BUDGET: Cell<Option<Budget>> = const { Cell::new(None) };
}

pub(super) fn decode_detail(bytes: &[u8]) -> Result<payload::MatchRecognizeRel> {
    if bytes.len() > MAX_DETAIL_BYTES {
        return plan_err!("MATCH_RECOGNIZE detail exceeds {MAX_DETAIL_BYTES} bytes");
    }
    let _scope =
        DetailScope(BUDGET.with(|budget| budget.replace(Some(Budget::default()))));
    charge_wire_fields(bytes)
        .map_err(|error| DataFusionError::Plan(error.to_string()))?;
    payload::MatchRecognizeRel::decode(bytes)
        .map_err(|error| DataFusionError::Plan(error.to_string()))
}

// Prost exposes no replacement constructor for custom Message errors yet.
#[allow(deprecated)]
pub(super) fn charge_wire_fields(
    mut bytes: &[u8],
) -> std::result::Result<(), DecodeError> {
    let previous = BUDGET.with(Cell::get);
    let mut budget = previous.unwrap_or_default();
    while !bytes.is_empty() {
        if budget.elements == MAX_SOURCE_ELEMENTS {
            return Err(DecodeError::new(format!(
                "MATCH_RECOGNIZE detail exceeds {MAX_SOURCE_ELEMENTS} wire fields"
            )));
        }
        let (tag, wire_type) = decode_key(&mut bytes)?;
        skip_field(wire_type, tag, &mut bytes, DecodeContext::default())?;
        budget.elements += 1;
    }
    if previous.is_some() {
        BUDGET.with(|state| state.set(Some(budget)));
    }
    Ok(())
}

struct DetailScope(Option<Budget>);

impl Drop for DetailScope {
    fn drop(&mut self) {
        BUDGET.with(|budget| budget.set(self.0));
    }
}

/// Prost's fixed limit counts both SourceExpression and its operation wrapper.
/// Reset that context only for source nodes, using these semantic depth/field
/// limits instead. Decoding is synchronous; scope guards restore thread state
/// after success, errors or unwinding. Other messages keep Prost's own limit.
/// Each recognized oneof field counts toward `MAX_SOURCE_FIELDS`, while
/// top-level and repeated-expression wire fields (including empty or
/// unknown-only elements) are bounded by `MAX_SOURCE_ELEMENTS`.
pub(super) struct ExpressionScope {
    owns_budget: bool,
}

impl ExpressionScope {
    // Prost exposes no replacement constructor for custom Message errors yet.
    #[allow(deprecated)]
    pub(super) fn enter() -> std::result::Result<Self, DecodeError> {
        let previous = BUDGET.with(Cell::get);
        let mut budget = previous.unwrap_or_default();
        if budget.depth == MAX_SOURCE_DEPTH {
            return Err(DecodeError::new(format!(
                "MATCH_RECOGNIZE source expression exceeds depth {MAX_SOURCE_DEPTH}"
            )));
        }
        if budget.fields == MAX_SOURCE_FIELDS {
            return Err(DecodeError::new(format!(
                "MATCH_RECOGNIZE source expressions exceed {MAX_SOURCE_FIELDS} kind fields"
            )));
        }
        budget.depth += 1;
        budget.fields += 1;
        BUDGET.with(|state| state.set(Some(budget)));
        Ok(Self {
            owns_budget: previous.is_none(),
        })
    }
}

impl Drop for ExpressionScope {
    fn drop(&mut self) {
        BUDGET.with(|state| {
            if self.owns_budget {
                state.set(None);
            } else {
                let mut budget = state.get().expect("source decode budget is active");
                budget.depth -= 1;
                state.set(Some(budget));
            }
        });
    }
}