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.

//! Compare the maintained wire declarations with Prost output from the schema.

use std::collections::BTreeMap;
use std::{fs, io};

use syn::{Attribute, Expr, Fields, GenericArgument, Item, Lit, PathArguments, Type};

fn attributes(attributes: &[Attribute]) -> syn::Result<String> {
    let mut wire = BTreeMap::new();
    for attribute in attributes
        .iter()
        .filter(|attribute| attribute.path().is_ident("prost"))
    {
        attribute.parse_nested_meta(|meta| {
            let name = meta.path.get_ident().expect("Prost attribute").to_string();
            if name == "boxed" {
                return Ok(());
            }
            let value = if meta.input.peek(syn::Token![=]) {
                let value: syn::LitStr = meta.value()?.parse()?;
                value.value()
            } else {
                String::new()
            };
            let value = if name == "tags" {
                value
                    .split(',')
                    .map(str::trim)
                    .collect::<Vec<_>>()
                    .join(",")
            } else {
                value.trim_start_matches("super::").to_string()
            };
            wire.insert(name, value);
            Ok(())
        })?;
    }
    Ok(format!("{wire:?}"))
}

fn type_shape(data_type: &Type) -> syn::Result<String> {
    let Type::Path(path) = data_type else {
        return Err(syn::Error::new_spanned(
            data_type,
            "expected a named wire type",
        ));
    };
    let part = path.path.segments.last().expect("named type");
    let arguments = match &part.arguments {
        PathArguments::None => Vec::new(),
        PathArguments::AngleBracketed(arguments) => arguments
            .args
            .iter()
            .map(|argument| {
                let GenericArgument::Type(data_type) = argument else {
                    return Err(syn::Error::new_spanned(
                        argument,
                        "expected a type argument",
                    ));
                };
                type_shape(data_type)
            })
            .collect::<syn::Result<Vec<_>>>()?,
        _ => {
            return Err(syn::Error::new_spanned(
                data_type,
                "unsupported wire type arguments",
            ));
        }
    };
    // Boxing is Rust layout; Option/Vec and Prost annotations carry presence.
    if part.ident == "Box" {
        assert_eq!(arguments.len(), 1);
        return Ok(arguments[0].clone());
    }
    let names = path
        .path
        .segments
        .iter()
        .map(|part| part.ident.to_string())
        .collect::<Vec<_>>();
    let name = if matches!(part.ident.to_string().as_str(), "Option" | "Vec" | "String") {
        part.ident.to_string()
    } else if let Some(index) = names.iter().position(|name| name == "proto") {
        format!("substrait::{}", names[index + 1..].join("::"))
    } else {
        names
            .iter()
            .filter(|name| name.as_str() != "super")
            .cloned()
            .collect::<Vec<_>>()
            .join("::")
    };
    Ok(if arguments.is_empty() {
        name
    } else {
        format!("{name}<{}>", arguments.join(","))
    })
}

fn enum_number(expression: &Expr) -> syn::Result<i64> {
    match expression {
        Expr::Lit(value) => match &value.lit {
            Lit::Int(value) => value.base10_parse(),
            _ => Err(syn::Error::new_spanned(
                expression,
                "expected an enum number",
            )),
        },
        Expr::Unary(value) if matches!(value.op, syn::UnOp::Neg(_)) => {
            Ok(-enum_number(&value.expr)?)
        }
        _ => Err(syn::Error::new_spanned(
            expression,
            "expected an enum number",
        )),
    }
}

fn declarations(
    items: &[Item],
    prefix: &str,
    wire: &mut BTreeMap<String, String>,
) -> syn::Result<()> {
    for item in items {
        match item {
            Item::Struct(message) => {
                let name = format!("{prefix}{}", message.ident);
                wire.insert(name.clone(), "message".to_string());
                for field in &message.fields {
                    let field_name = field.ident.as_ref().expect("named message field");
                    // SourceExpression has a guarded custom Message implementation.
                    // Its complete Kind alternatives below still match the schema.
                    let metadata = if name == "SourceExpression" && field_name == "kind" {
                        String::new()
                    } else {
                        attributes(&field.attrs)?
                    };
                    wire.insert(
                        format!("{name}.{field_name}"),
                        format!("{metadata}:{}", type_shape(&field.ty)?),
                    );
                }
            }
            Item::Enum(enumeration) => {
                let name = format!("{prefix}{}", enumeration.ident);
                wire.insert(name.clone(), "enum".to_string());
                for variant in &enumeration.variants {
                    let value = if let Some((_, value)) = &variant.discriminant {
                        enum_number(value)?.to_string()
                    } else if let Fields::Unnamed(fields) = &variant.fields {
                        assert_eq!(fields.unnamed.len(), 1);
                        format!(
                            "{}:{}",
                            attributes(&variant.attrs)?,
                            type_shape(&fields.unnamed[0].ty)?
                        )
                    } else {
                        return Err(syn::Error::new_spanned(
                            variant,
                            "expected a wire enum or oneof",
                        ));
                    };
                    wire.insert(format!("{name}::{}", variant.ident), value);
                }
            }
            Item::Mod(module) => {
                if let Some((_, items)) = &module.content {
                    declarations(items, &format!("{prefix}{}::", module.ident), wire)?;
                }
            }
            _ => {}
        }
    }
    Ok(())
}

fn wire_contract(source: &str) -> syn::Result<BTreeMap<String, String>> {
    let mut wire = BTreeMap::new();
    declarations(&syn::parse_file(source)?.items, "", &mut wire)?;
    Ok(wire)
}

fn generated_reference() -> io::Result<String> {
    let directory = tempfile::tempdir()?;
    let descriptor = directory.path().join("substrait.pb");
    fs::write(&descriptor, substrait::proto::FILE_DESCRIPTOR_SET)?;
    let schema = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("proto/match_recognize.proto");
    prost_build::Config::new()
        .out_dir(directory.path())
        .extern_path(".substrait", "::datafusion_substrait::substrait::proto")
        .protoc_arg(format!("--descriptor_set_in={}", descriptor.display()))
        .compile_protos(
            std::slice::from_ref(&schema),
            &[schema.parent().expect("schema directory")],
        )?;
    let package = crate::substrait::MATCH_RECOGNIZE_TYPE_URL
        .rsplit_once('.')
        .expect("message type")
        .0
        .rsplit('/')
        .next()
        .expect("package");
    fs::read_to_string(directory.path().join(format!("{package}.rs")))
}

#[test]
fn wire_declarations_match_proto_and_detect_drift()
-> Result<(), Box<dyn std::error::Error>> {
    let expected = wire_contract(&generated_reference()?)?;
    let source = include_str!("payload.rs");
    assert_eq!(wire_contract(source)?, expected);
    for (from, to) in [
        ("tag = \"1\"", "tag = \"99\""),
        ("uint32, optional", "fixed32, optional"),
        ("OneRow = 1", "OneRow = 99"),
    ] {
        let changed = source.replacen(from, to, 1);
        assert_ne!(changed, source, "mutation must change {from}");
        assert_ne!(
            wire_contract(&changed)?,
            expected,
            "missed schema drift: {from}"
        );
    }
    Ok(())
}