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.

use super::*;
use crate::planning::logical::MetadataEndpoint;
use datafusion::arrow::array::{Int64Array, StringArray};

enum Values {
    Classifier(StringBuilder),
    Sequence(Int64Builder),
}

fn label(names: &[Option<String>], word: u64) -> Result<Option<&str>> {
    if word == 0 {
        return Ok(None);
    }
    usize::try_from(word)
        .ok()
        .and_then(|index| names.get(index))
        .and_then(Option::as_deref)
        .map(Some)
        .ok_or_else(|| {
            DataFusionError::Internal(format!("unknown selected classifier id {word}"))
        })
}

/// Size and admit one output batch before constructing its metadata array.
/// Both passes report bounded work; the finished array retains the reservation.
pub(super) fn materialize(
    endpoint: MetadataEndpoint,
    words: &[u64],
    names: &[Option<String>],
    memory: &MemoryReservation,
    completed: &mut dyn FnMut(usize) -> Result<()>,
) -> Result<(ArrayRef, MemoryReservation)> {
    let include_empty = matches!(
        endpoint,
        MetadataEndpoint::Sequence {
            include_empty: true,
            ..
        }
    );
    let classifier = matches!(endpoint, MetadataEndpoint::Classifier { .. });
    let mut nullable = false;
    let mut string_bytes = 0usize;
    // Empty arrays still report each completed pass, as nonempty arrays do.
    let chunks = || {
        words
            .chunks(COARSE_WORK_BATCH_SIZE)
            .chain(words.is_empty().then_some(words))
    };
    for chunk in chunks() {
        nullable |= !include_empty && chunk.contains(&0);
        if classifier {
            for &word in chunk {
                string_bytes = string_bytes
                    .checked_add(label(names, word)?.map_or(0, str::len))
                    .filter(|&n| i32::try_from(n).is_ok())
                    .ok_or_else(|| {
                        super::super::resource_error(
                            "classifier data exceeds Utf8 offset capacity".into(),
                        )
                    })?;
            }
        }
        completed(chunk.len())?;
    }
    // The input Vec<u64> already fits isize. Arrow uses Vec capacities for
    // offsets/values and a 64-byte-rounded bitmap only when a NULL occurs.
    let validity = if nullable {
        words.len().div_ceil(8).next_multiple_of(64)
    } else {
        0
    };
    let bytes = if classifier {
        size_of::<StringArray>() + (words.len() + 1) * size_of::<i32>() + string_bytes
    } else {
        size_of::<Int64Array>() + size_of_val(words)
    };
    let lease = memory.new_empty();
    lease.try_grow(bytes + validity)?;
    let mut output = if classifier {
        Values::Classifier(StringBuilder::with_capacity(words.len(), string_bytes))
    } else {
        Values::Sequence(Int64Builder::with_capacity(words.len()))
    };
    for chunk in chunks() {
        match &mut output {
            Values::Classifier(builder) => {
                for &word in chunk {
                    builder.append_option(label(names, word)?);
                }
            }
            Values::Sequence(builder) => {
                for &word in chunk {
                    let value = i64::try_from(word).map_err(|_| {
                        DataFusionError::Execution("match sequence exceeds Int64".into())
                    })?;
                    builder.append_option(
                        (word != 0 || include_empty).then_some(value.max(1)),
                    );
                }
            }
        }
        completed(chunk.len())?;
    }
    let array: ArrayRef = match output {
        Values::Classifier(mut b) => Arc::new(b.finish()),
        Values::Sequence(mut b) => Arc::new(b.finish()),
    };
    debug_assert_eq!(array.get_array_memory_size(), lease.size());
    Ok((array, lease))
}

#[cfg(test)]
mod tests {
    use super::*;
    use datafusion::execution::memory_pool::{
        GreedyMemoryPool, MemoryConsumer, MemoryPool,
    };

    #[test]
    fn endpoint_flush_reserves_before_allocating_and_releases_on_drop() -> Result<()> {
        let names = [None, Some("é".repeat(2048))];
        let rows = COARSE_WORK_BATCH_SIZE * 2 + 1;
        let mut words = vec![1; rows];
        words[rows - 1] = 0;
        for endpoint in [
            MetadataEndpoint::Classifier { last: false },
            MetadataEndpoint::Sequence {
                last: true,
                include_empty: false,
            },
            MetadataEndpoint::Sequence {
                last: true,
                include_empty: true,
            },
        ] {
            for limit in [1, 1 << 20] {
                let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
                let lease = MemoryConsumer::new("metadata flush").register(&pool);
                let mut work = Vec::new();
                let result =
                    materialize(endpoint, &words, &names, &lease, &mut |units| {
                        assert!(units <= COARSE_WORK_BATCH_SIZE);
                        work.push(units);
                        Ok(())
                    });
                match result {
                    Ok((array, held)) => {
                        assert!(limit > 1);
                        assert_eq!(held.size(), array.get_array_memory_size());
                        assert_eq!(array.len(), rows);
                        match endpoint {
                            MetadataEndpoint::Classifier { .. } => {
                                let text =
                                    array.as_any().downcast_ref::<StringArray>().unwrap();
                                assert_eq!(text.value(0), names[1].as_ref().unwrap());
                                assert!(text.is_null(rows - 1));
                            }
                            MetadataEndpoint::Sequence { include_empty, .. } => {
                                let seq =
                                    array.as_any().downcast_ref::<Int64Array>().unwrap();
                                assert_eq!(seq.value(0), 1);
                                assert_eq!(seq.is_valid(rows - 1), include_empty);
                                if include_empty {
                                    assert_eq!(seq.value(rows - 1), 1);
                                }
                            }
                        }
                    }
                    Err(DataFusionError::ResourcesExhausted(_)) if limit == 1 => {}
                    Err(e) => return Err(e),
                }

                assert_eq!(pool.reserved(), 0);
                let pass_work = [COARSE_WORK_BATCH_SIZE, COARSE_WORK_BATCH_SIZE, 1];
                if limit > 1 {
                    assert_eq!(work, pass_work.repeat(2));
                    // Interrupt construction after admission. The local array and
                    // its reservation must be discarded together on callback failure.
                    let error =
                        materialize(endpoint, &words, &names, &lease, &mut |units| {
                            assert!(units <= COARSE_WORK_BATCH_SIZE);
                            if pool.reserved() != 0 {
                                return internal_err!(
                                    "injected construction cancellation"
                                );
                            }
                            Ok(())
                        })
                        .unwrap_err();
                    assert!(
                        error
                            .to_string()
                            .contains("injected construction cancellation")
                    );
                    assert_eq!(pool.reserved(), 0);
                } else {
                    assert_eq!(work, pass_work);
                }
            }
        }
        Ok(())
    }

    #[test]
    fn validation_order_and_empty_passes_preserve_reservation_ownership() -> Result<()> {
        let names = [None, Some("A".into())];
        for endpoint in [
            MetadataEndpoint::Classifier { last: false },
            MetadataEndpoint::Sequence {
                last: false,
                include_empty: false,
            },
        ] {
            for limit in [1, 4096] {
                let pool: Arc<dyn MemoryPool> = Arc::new(GreedyMemoryPool::new(limit));
                let lease = MemoryConsumer::new("metadata validation").register(&pool);
                let mut work = Vec::new();
                let error =
                    materialize(endpoint, &[u64::MAX], &names, &lease, &mut |units| {
                        work.push(units);
                        Ok(())
                    })
                    .unwrap_err();
                match endpoint {
                    MetadataEndpoint::Classifier { .. } => {
                        assert!(matches!(error, DataFusionError::Internal(_)));
                        assert!(
                            work.is_empty(),
                            "classifier validation precedes admission"
                        );
                    }
                    MetadataEndpoint::Sequence { .. } => {
                        assert_eq!(
                            work,
                            [1],
                            "sequence validation follows sizing and admission"
                        );
                        if limit == 1 {
                            assert!(matches!(
                                error,
                                DataFusionError::ResourcesExhausted(_)
                            ));
                        } else {
                            assert!(matches!(error, DataFusionError::Execution(_)));
                        }
                    }
                }
                assert_eq!(pool.reserved(), 0);
                if limit > 1 {
                    work.clear();
                    let (array, held) =
                        materialize(endpoint, &[], &names, &lease, &mut |units| {
                            work.push(units);
                            Ok(())
                        })?;
                    assert_eq!(work, [0, 0]);
                    assert!(array.is_empty());
                    assert_eq!(held.size(), array.get_array_memory_size());
                    drop((array, held));
                    assert_eq!(pool.reserved(), 0);
                }
            }
        }
        Ok(())
    }
}