diff --git a/Cargo.lock b/Cargo.lock index 336d69d12547a..5bd4a3acac77f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2181,6 +2181,7 @@ dependencies = [ "datafusion-common", "datafusion-expr", "datafusion-physical-expr-common", + "datafusion-proto-models", "futures", "insta", "log", diff --git a/datafusion/execution/Cargo.toml b/datafusion/execution/Cargo.toml index eec8b99f99495..4f22933374e6d 100644 --- a/datafusion/execution/Cargo.toml +++ b/datafusion/execution/Cargo.toml @@ -37,6 +37,9 @@ arrow_buffer_pool = [ "arrow-buffer/pool", ] sql = [] +# Exposes the `proto` module: the registry decoders for stateful scalar, +# aggregate, window and higher-order functions. +proto = ["dep:datafusion-proto-models"] [dependencies] arrow = { workspace = true } @@ -47,6 +50,7 @@ dashmap = { workspace = true } datafusion-common = { workspace = true, default-features = false } datafusion-expr = { workspace = true, default-features = false } datafusion-physical-expr-common = { workspace = true, default-features = false } +datafusion-proto-models = { workspace = true, optional = true } futures = { workspace = true } log = { workspace = true } object_store = { workspace = true, features = ["fs"] } diff --git a/datafusion/execution/src/lib.rs b/datafusion/execution/src/lib.rs index 4f3ce798c21ae..604a120ea0cea 100644 --- a/datafusion/execution/src/lib.rs +++ b/datafusion/execution/src/lib.rs @@ -22,6 +22,8 @@ pub mod memory_pool; pub mod object_store; #[cfg(feature = "parquet_encryption")] pub mod parquet_encryption; +#[cfg(feature = "proto")] +pub mod proto; pub mod runtime_env; pub mod spill_file; mod stream; diff --git a/datafusion/execution/src/proto.rs b/datafusion/execution/src/proto.rs new file mode 100644 index 0000000000000..b631ca812bb0c --- /dev/null +++ b/datafusion/execution/src/proto.rs @@ -0,0 +1,251 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! The function faces of the session-scoped [`ProtoDecoderRegistry`]. +//! +//! A stateful function writes its state with its `try_encode_state` hook. +//! The wire carries the state's `type_name` next to the instance's SQL name. +//! The decoding session rebuilds the instance with the decoder registered +//! under that type name. +//! +//! | Function kind | Encode hook | Decoder trait | +//! |---|---|---| +//! | Scalar | [`ScalarUDFImpl::try_encode_state`] | [`ScalarUdfFromProto`] | +//! | Aggregate | [`AggregateUDFImpl::try_encode_state`] | [`AggregateUdfFromProto`] | +//! | Window | [`WindowUDFImpl::try_encode_state`] | [`WindowUdfFromProto`] | +//! | Higher-order | [`HigherOrderUDFImpl::try_encode_state`] | [`HigherOrderUdfFromProto`] | +//! +//! [`ScalarUDFImpl::try_encode_state`]: datafusion_expr::ScalarUDFImpl::try_encode_state +//! [`AggregateUDFImpl::try_encode_state`]: datafusion_expr::AggregateUDFImpl::try_encode_state +//! [`WindowUDFImpl::try_encode_state`]: datafusion_expr::WindowUDFImpl::try_encode_state +//! [`HigherOrderUDFImpl::try_encode_state`]: datafusion_expr::HigherOrderUDFImpl::try_encode_state + +use std::sync::Arc; + +use datafusion_common::Result; +use datafusion_expr::{AggregateUDF, HigherOrderUDF, ScalarUDF, WindowUDF}; +pub use datafusion_proto_models::ProtoDecoderRegistry; + +use crate::TaskContext; + +/// The constructor that rebuilds a stateful scalar UDF from the +/// [`UDFState`](datafusion_expr::UDFState) its +/// [`try_encode_state`](datafusion_expr::ScalarUDFImpl::try_encode_state) +/// wrote. +pub trait ScalarUdfFromProto: 'static { + /// The registry key. It must equal the `type_name` that + /// `try_encode_state` writes. Namespace it with the owning crate. + const NAME: &'static str; + + /// Rebuild the function from `payload`. `name` is the SQL name the + /// instance was written under, and the returned function must report it + /// from [`ScalarUDF::name`]. + fn try_from_proto( + payload: &[u8], + name: &str, + ctx: &TaskContext, + ) -> Result>; + + /// Register this decoder in `registry`, under [`Self::NAME`]. + fn register_proto(registry: &mut ProtoDecoderRegistry) -> Result<()> { + registry.register_decoder::( + Self::NAME, + Self::try_from_proto, + ) + } +} + +type ScalarUdfDecoder = fn(&[u8], &str, &TaskContext) -> Result>; + +/// Decode `payload` with the scalar UDF decoder registered under +/// `type_name`. `None` means no decoder is registered under `type_name`. +/// +/// # Public Only for Internal Use: +/// +/// This is not a public API and is for internal use only; see [API policy] for details. +/// +/// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis +#[doc(hidden)] +pub fn decode_scalar_udf( + registry: &ProtoDecoderRegistry, + type_name: &str, + payload: &[u8], + name: &str, + ctx: &TaskContext, +) -> Option>> { + let decoder = registry.decoder::(type_name)?; + Some(decoder(payload, name, ctx)) +} + +/// Every scalar UDF type name registered in `registry`, in arbitrary order. +pub fn scalar_udf_names(registry: &ProtoDecoderRegistry) -> impl Iterator { + registry.names::() +} + +/// The constructor that rebuilds a stateful aggregate UDF from the +/// [`UDFState`](datafusion_expr::UDFState) its +/// [`try_encode_state`](datafusion_expr::AggregateUDFImpl::try_encode_state) +/// wrote. +pub trait AggregateUdfFromProto: 'static { + /// The registry key. It must equal the `type_name` that + /// `try_encode_state` writes. Namespace it with the owning crate. + const NAME: &'static str; + + /// Rebuild the function from `payload`. `name` is the SQL name the + /// instance was written under, and the returned function must report it + /// from [`AggregateUDF::name`]. + fn try_from_proto( + payload: &[u8], + name: &str, + ctx: &TaskContext, + ) -> Result>; + + /// Register this decoder in `registry`, under [`Self::NAME`]. + fn register_proto(registry: &mut ProtoDecoderRegistry) -> Result<()> { + registry.register_decoder::( + Self::NAME, + Self::try_from_proto, + ) + } +} + +type AggregateUdfDecoder = fn(&[u8], &str, &TaskContext) -> Result>; + +/// Decode `payload` with the aggregate UDF decoder registered under +/// `type_name`. `None` means no decoder is registered under `type_name`. +/// +/// # Public Only for Internal Use: +/// +/// This is not a public API and is for internal use only; see [API policy] for details. +/// +/// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis +#[doc(hidden)] +pub fn decode_aggregate_udf( + registry: &ProtoDecoderRegistry, + type_name: &str, + payload: &[u8], + name: &str, + ctx: &TaskContext, +) -> Option>> { + let decoder = registry.decoder::(type_name)?; + Some(decoder(payload, name, ctx)) +} + +/// Every aggregate UDF type name registered in `registry`, in arbitrary order. +pub fn aggregate_udf_names( + registry: &ProtoDecoderRegistry, +) -> impl Iterator { + registry.names::() +} + +/// The constructor that rebuilds a stateful window UDF from the +/// [`UDFState`](datafusion_expr::UDFState) its +/// [`try_encode_state`](datafusion_expr::WindowUDFImpl::try_encode_state) +/// wrote. +pub trait WindowUdfFromProto: 'static { + /// The registry key. It must equal the `type_name` that + /// `try_encode_state` writes. Namespace it with the owning crate. + const NAME: &'static str; + + /// Rebuild the function from `payload`. `name` is the SQL name the + /// instance was written under, and the returned function must report it + /// from [`WindowUDF::name`]. + fn try_from_proto( + payload: &[u8], + name: &str, + ctx: &TaskContext, + ) -> Result>; + + /// Register this decoder in `registry`, under [`Self::NAME`]. + fn register_proto(registry: &mut ProtoDecoderRegistry) -> Result<()> { + registry.register_decoder::( + Self::NAME, + Self::try_from_proto, + ) + } +} + +type WindowUdfDecoder = fn(&[u8], &str, &TaskContext) -> Result>; + +/// Decode `payload` with the window UDF decoder registered under +/// `type_name`. `None` means no decoder is registered under `type_name`. +/// +/// # Public Only for Internal Use: +/// +/// This is not a public API and is for internal use only; see [API policy] for details. +/// +/// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis +#[doc(hidden)] +pub fn decode_window_udf( + registry: &ProtoDecoderRegistry, + type_name: &str, + payload: &[u8], + name: &str, + ctx: &TaskContext, +) -> Option>> { + let decoder = registry.decoder::(type_name)?; + Some(decoder(payload, name, ctx)) +} + +/// Every window UDF type name registered in `registry`, in arbitrary order. +pub fn window_udf_names(registry: &ProtoDecoderRegistry) -> impl Iterator { + registry.names::() +} + +/// The constructor that rebuilds a stateful higher-order function from the +/// [`UDFState`](datafusion_expr::UDFState) its +/// [`try_encode_state`](datafusion_expr::HigherOrderUDFImpl::try_encode_state) +/// wrote. +pub trait HigherOrderUdfFromProto: 'static { + /// The registry key. It must equal the `type_name` that + /// `try_encode_state` writes. Namespace it with the owning crate. + const NAME: &'static str; + + /// Rebuild the function from `payload`. `name` is the SQL name the + /// instance was written under, and the returned function must report it + /// from [`HigherOrderUDF::name`]. + fn try_from_proto( + payload: &[u8], + name: &str, + ctx: &TaskContext, + ) -> Result>; + + /// Register this decoder in `registry`, under [`Self::NAME`]. + fn register_proto(registry: &mut ProtoDecoderRegistry) -> Result<()> { + registry.register_decoder::( + Self::NAME, + Self::try_from_proto, + ) + } +} + +type HigherOrderUdfDecoder = fn(&[u8], &str, &TaskContext) -> Result>; + +/// Decode `payload` with the higher-order function decoder registered under +/// `type_name`. `None` means no decoder is registered under `type_name`. +/// +/// # Public Only for Internal Use: +/// +/// This is not a public API and is for internal use only; see [API policy] for details. +/// +/// [API policy]: https://datafusion.apache.org/contributor-guide/api-health.html#internal-public-apis +#[doc(hidden)] +pub fn decode_higher_order_udf( + registry: &ProtoDecoderRegistry, + type_name: &str, + payload: &[u8], + name: &str, + ctx: &TaskContext, +) -> Option>> { + let decoder = registry.decoder::(type_name)?; + Some(decoder(payload, name, ctx)) +} + +/// Every higher-order function type name registered in `registry`, in +/// arbitrary order. +pub fn higher_order_udf_names( + registry: &ProtoDecoderRegistry, +) -> impl Iterator { + registry.names::() +} diff --git a/datafusion/expr/src/async_udf.rs b/datafusion/expr/src/async_udf.rs index 6aa863016e3f7..391750fd35b38 100644 --- a/datafusion/expr/src/async_udf.rs +++ b/datafusion/expr/src/async_udf.rs @@ -93,6 +93,10 @@ impl ScalarUDFImpl for AsyncScalarUDF { self.inner.name() } + fn try_encode_state(&self) -> Result> { + self.inner.try_encode_state() + } + fn signature(&self) -> &Signature { self.inner.signature() } diff --git a/datafusion/expr/src/higher_order_function.rs b/datafusion/expr/src/higher_order_function.rs index 92aaf0572a52b..0a278cfe8a7f5 100644 --- a/datafusion/expr/src/higher_order_function.rs +++ b/datafusion/expr/src/higher_order_function.rs @@ -10,7 +10,7 @@ use crate::expr::{ }; use crate::type_coercion::functions::value_fields_with_higher_order_udf; use crate::udf_eq::UdfEq; -use crate::{ColumnarValue, Documentation, Expr, ExprSchemable}; +use crate::{ColumnarValue, Documentation, Expr, ExprSchemable, UDFState}; use arrow::array::{ArrayRef, RecordBatch, RecordBatchOptions}; use arrow::datatypes::{DataType, FieldRef, Schema}; use arrow_schema::SchemaRef; @@ -511,6 +511,18 @@ pub trait HigherOrderUDFImpl: Debug + DynEq + DynHash + Send + Sync + Any { /// Returns this function's name fn name(&self) -> &str; + /// The state of this function instance, for serialization. + /// + /// `Ok(None)` (the default) means the function carries no state and the + /// decoding session resolves it by [`Self::name`]. `Ok(Some(state))` + /// means the decoding session rebuilds the instance from + /// `state.payload` with the decoder registered under `state.type_name` + /// (see `datafusion_execution::proto::HigherOrderUdfFromProto`, behind + /// the `proto` feature). + fn try_encode_state(&self) -> Result> { + Ok(None) + } + /// Returns any aliases (alternate names) for this function. /// /// Aliases can be used to invoke the same function using different names. @@ -965,6 +977,11 @@ impl HigherOrderUDF { self.inner.name() } + /// See [`HigherOrderUDFImpl::try_encode_state`]. + pub fn try_encode_state(&self) -> Result> { + self.inner.try_encode_state() + } + /// Returns the aliases for this function. /// /// See [`HigherOrderUDF::with_aliases`] for more details. @@ -1099,6 +1116,10 @@ impl HigherOrderUDFImpl for AliasedHigherOrderUDFImpl { self.inner.name() } + fn try_encode_state(&self) -> Result> { + self.inner.try_encode_state() + } + fn aliases(&self) -> &[String] { &self.aliases } diff --git a/datafusion/expr/src/lib.rs b/datafusion/expr/src/lib.rs index a6dd1e7bca914..2647a30544cd8 100644 --- a/datafusion/expr/src/lib.rs +++ b/datafusion/expr/src/lib.rs @@ -145,6 +145,7 @@ pub use udaf::{ }; pub use udf::{ ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, StructFieldMapping, + UDFState, }; pub use udwf::{LimitEffect, ReversedUDWF, WindowUDF, WindowUDFImpl}; pub use window_frame::{WindowFrame, WindowFrameBound, WindowFrameUnits}; diff --git a/datafusion/expr/src/udaf.rs b/datafusion/expr/src/udaf.rs index 7e19280834c63..31887a1b30541 100644 --- a/datafusion/expr/src/udaf.rs +++ b/datafusion/expr/src/udaf.rs @@ -33,7 +33,7 @@ use crate::groups_accumulator::GroupsAccumulator; use crate::udf_eq::UdfEq; use crate::utils::{AggregateOrderSensitivity, format_state_name, ordering_state_fields}; use crate::{Accumulator, Expr, expr_vec_fmt}; -use crate::{Documentation, Signature}; +use crate::{Documentation, Signature, UDFState}; /// Logical representation of a user-defined [aggregate function] (UDAF). /// @@ -162,6 +162,11 @@ impl AggregateUDF { self.inner.name() } + /// See [`AggregateUDFImpl::try_encode_state`]. + pub fn try_encode_state(&self) -> Result> { + self.inner.try_encode_state() + } + /// Returns the aliases for this function. pub fn aliases(&self) -> &[String] { self.inner.aliases() @@ -452,6 +457,18 @@ pub trait AggregateUDFImpl: Debug + DynEq + DynHash + Send + Sync + Any { /// Returns this function's name fn name(&self) -> &str; + /// The state of this function instance, for serialization. + /// + /// `Ok(None)` (the default) means the function carries no state and the + /// decoding session resolves it by [`Self::name`]. `Ok(Some(state))` + /// means the decoding session rebuilds the instance from + /// `state.payload` with the decoder registered under `state.type_name` + /// (see `datafusion_execution::proto::AggregateUdfFromProto`, behind the + /// `proto` feature). + fn try_encode_state(&self) -> Result> { + Ok(None) + } + /// Returns any aliases (alternate names) for this function. /// /// Note: `aliases` should only include names other than [`Self::name`]. @@ -1568,6 +1585,10 @@ impl AggregateUDFImpl for AliasedAggregateUDFImpl { self.inner.name() } + fn try_encode_state(&self) -> Result> { + self.inner.try_encode_state() + } + fn signature(&self) -> &Signature { self.inner.signature() } diff --git a/datafusion/expr/src/udf.rs b/datafusion/expr/src/udf.rs index c3c9e461e307a..77b476f93161a 100644 --- a/datafusion/expr/src/udf.rs +++ b/datafusion/expr/src/udf.rs @@ -383,6 +383,11 @@ impl ScalarUDF { self.inner.documentation() } + /// See [`ScalarUDFImpl::try_encode_state`]. + pub fn try_encode_state(&self) -> Result> { + self.inner.try_encode_state() + } + /// Return true if this function is an async function pub fn as_async(&self) -> Option<&AsyncScalarUDF> { self.inner().downcast_ref::() @@ -608,6 +613,18 @@ pub trait ScalarUDFImpl: Debug + DynEq + DynHash + Send + Sync + Any { None } + /// The state of this function instance, for serialization. + /// + /// `Ok(None)` (the default) means the function carries no state and the + /// decoding session resolves it by [`Self::name`]. `Ok(Some(state))` + /// means the decoding session rebuilds the instance from + /// `state.payload` with the decoder registered under `state.type_name` + /// (see `datafusion_execution::proto::ScalarUdfFromProto`, behind the + /// `proto` feature). + fn try_encode_state(&self) -> Result> { + Ok(None) + } + /// What type will be returned by this function, given the arguments? /// /// By default, this function calls [`Self::return_type`] with the @@ -1118,6 +1135,20 @@ impl dyn ScalarUDFImpl { } } +/// The serialized state of a stateful function, returned by +/// [`ScalarUDFImpl::try_encode_state`], +/// [`AggregateUDFImpl::try_encode_state`](crate::AggregateUDFImpl::try_encode_state), +/// [`WindowUDFImpl::try_encode_state`](crate::WindowUDFImpl::try_encode_state) +/// and [`HigherOrderUDFImpl::try_encode_state`](crate::HigherOrderUDFImpl::try_encode_state). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UDFState { + /// The key of the decoder that rebuilds the function. It names the + /// implementing type, not the SQL name of one instance. + pub type_name: &'static str, + /// The instance's state. An empty payload is still a payload. + pub payload: Vec, +} + /// ScalarUDF that adds an alias to the underlying function. It is better to /// implement [`ScalarUDFImpl`], which supports aliases, directly if possible. #[derive(Debug, PartialEq, Eq, Hash)] @@ -1178,6 +1209,10 @@ impl ScalarUDFImpl for AliasedScalarUDFImpl { None } + fn try_encode_state(&self) -> Result> { + self.inner.try_encode_state() + } + fn aliases(&self) -> &[String] { &self.aliases } diff --git a/datafusion/expr/src/udwf.rs b/datafusion/expr/src/udwf.rs index 29de1ac47f964..0083226795a84 100644 --- a/datafusion/expr/src/udwf.rs +++ b/datafusion/expr/src/udwf.rs @@ -18,7 +18,7 @@ use arrow::datatypes::{DataType, FieldRef}; use crate::expr::WindowFunction; use crate::udf_eq::UdfEq; use crate::{ - Expr, PartitionEvaluator, Signature, function::WindowFunctionSimplification, + Expr, PartitionEvaluator, Signature, UDFState, function::WindowFunctionSimplification, }; use datafusion_common::{Result, not_impl_err}; use datafusion_doc::Documentation; @@ -132,6 +132,11 @@ impl WindowUDF { self.inner.name() } + /// See [`WindowUDFImpl::try_encode_state`]. + pub fn try_encode_state(&self) -> Result> { + self.inner.try_encode_state() + } + /// Returns the aliases for this function. pub fn aliases(&self) -> &[String] { self.inner.aliases() @@ -303,6 +308,18 @@ pub trait WindowUDFImpl: Debug + DynEq + DynHash + Send + Sync + Any { /// Returns this function's name fn name(&self) -> &str; + /// The state of this function instance, for serialization. + /// + /// `Ok(None)` (the default) means the function carries no state and the + /// decoding session resolves it by [`Self::name`]. `Ok(Some(state))` + /// means the decoding session rebuilds the instance from + /// `state.payload` with the decoder registered under `state.type_name` + /// (see `datafusion_execution::proto::WindowUdfFromProto`, behind the + /// `proto` feature). + fn try_encode_state(&self) -> Result> { + Ok(None) + } + /// Returns any aliases (alternate names) for this function. /// /// Note: `aliases` should only include names other than [`Self::name`]. @@ -507,6 +524,10 @@ impl WindowUDFImpl for AliasedWindowUDFImpl { self.inner.name() } + fn try_encode_state(&self) -> Result> { + self.inner.try_encode_state() + } + fn signature(&self) -> &Signature { self.inner.signature() } diff --git a/datafusion/physical-plan/Cargo.toml b/datafusion/physical-plan/Cargo.toml index 25f8e437407a1..200b64628f464 100644 --- a/datafusion/physical-plan/Cargo.toml +++ b/datafusion/physical-plan/Cargo.toml @@ -35,6 +35,7 @@ tokio_coop_fallback = [] proto = [ "dep:datafusion-proto-models", "dep:datafusion-proto-common", + "datafusion-execution/proto", "datafusion-physical-expr/proto", "datafusion-physical-expr-common/proto", ] diff --git a/datafusion/physical-plan/src/aggregates/mod.rs b/datafusion/physical-plan/src/aggregates/mod.rs index d3f7c3c008be1..b9522e087aaaf 100644 --- a/datafusion/physical-plan/src/aggregates/mod.rs +++ b/datafusion/physical-plan/src/aggregates/mod.rs @@ -2683,7 +2683,10 @@ fn encode_aggregate_expr( )?; let name = aggr_expr.fun().name().to_string(); // The context already applies `(!buf.is_empty()).then_some(buf)`. - let fun_definition = ctx.encode_udaf(aggr_expr.fun())?; + let crate::proto::EncodedFunction { + payload: fun_definition, + type_name: fun_type_name, + } = ctx.encode_udaf_definition(aggr_expr.fun())?; let human_display = match (aggr_expr.human_display(), aggr_expr.human_display_alias()) { (Some(display), Some(alias)) => encode_human_display_alias(display, alias), @@ -2705,6 +2708,7 @@ fn encode_aggregate_expr( fun_definition, human_display, is_reversed: aggr_expr.is_reversed(), + fun_type_name, }, )), }) @@ -2852,8 +2856,11 @@ impl AggregateExec { }; // The context owns the payload-to-codec and // registry-to-codec fallback order. - let udaf = - ctx.decode_udaf(udaf_name, aggregate.fun_definition.as_deref())?; + let udaf = ctx.decode_udaf_definition( + udaf_name, + aggregate.fun_definition.as_deref(), + aggregate.fun_type_name.as_deref(), + )?; let (human_display, human_display_alias) = split_human_display_alias(&aggregate.human_display, name); let builder = AggregateExprBuilder::new(udaf, args) diff --git a/datafusion/physical-plan/src/proto/mod.rs b/datafusion/physical-plan/src/proto/mod.rs index 9fe5113affc15..66a451b9da410 100644 --- a/datafusion/physical-plan/src/proto/mod.rs +++ b/datafusion/physical-plan/src/proto/mod.rs @@ -61,10 +61,10 @@ pub mod registry; use std::sync::Arc; use arrow::datatypes::Schema; -use datafusion_common::{Result, internal_datafusion_err}; +use datafusion_common::{Result, internal_datafusion_err, not_impl_err}; use datafusion_execution::TaskContext; use datafusion_expr::physical_planning_context::ScalarSubqueryResults; -use datafusion_expr::{AggregateUDF, ScalarUDF, WindowUDF}; +use datafusion_expr::{AggregateUDF, ScalarUDF, UDFState, WindowUDF}; use datafusion_physical_expr::PhysicalExpr; pub use datafusion_physical_expr::proto::{ ExtensionExprFromProto, decode_physical_expr, extension_expr_node, @@ -117,6 +117,61 @@ pub trait ExecutionPlanEncode { /// Serialize a window UDF to an opaque payload. `None` means "decodable by /// name alone". fn encode_udwf(&self, udwf: &WindowUDF) -> Result>>; + + /// Serialize an aggregate UDF to its payload and, when the function wrote + /// its own state, the decoder type name. + /// + /// The state from [`AggregateUDF::try_encode_state`] wins over + /// [`Self::encode_udaf`], so no encoder can drop it. + fn encode_udaf_definition(&self, udaf: &AggregateUDF) -> Result { + match udaf.try_encode_state()? { + Some(state) => Ok(state.into()), + None => Ok(EncodedFunction { + payload: self.encode_udaf(udaf)?, + type_name: None, + }), + } + } + + /// Serialize a window UDF to its payload and, when the function wrote + /// its own state, the decoder type name. + /// + /// The state from [`WindowUDF::try_encode_state`] wins over + /// [`Self::encode_udwf`], so no encoder can drop it. + fn encode_udwf_definition(&self, udwf: &WindowUDF) -> Result { + match udwf.try_encode_state()? { + Some(state) => Ok(state.into()), + None => Ok(EncodedFunction { + payload: self.encode_udwf(udwf)?, + type_name: None, + }), + } + } +} + +/// A function definition as a plan node writes it: the `fun_definition` and +/// `fun_type_name` fields of the function's proto node. +/// +/// A `type_name` means the function wrote `payload` itself. The decoding +/// session then rebuilds it with the registry decoder for that name. Both +/// `None` means the function is decodable by name alone. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct EncodedFunction { + /// The function's serialized definition. + pub payload: Option>, + /// The registry key of the decoder for a self-encoded function. + pub type_name: Option, +} + +impl From for EncodedFunction { + /// The payload is kept even when empty, because `type_name` says the + /// function wrote it. + fn from(state: UDFState) -> Self { + Self { + payload: Some(state.payload), + type_name: Some(state.type_name.to_string()), + } + } } /// Internal dispatch trait backing [`ExecutionPlanDecodeCtx`]. @@ -168,6 +223,40 @@ pub trait ExecutionPlanDecode { /// Reconstruct a window UDF from its name and optional payload. fn decode_udwf(&self, name: &str, payload: Option<&[u8]>) -> Result>; + + /// Reconstruct an aggregate UDF from its name, optional payload and + /// optional self-encoded type name. + fn decode_udaf_definition( + &self, + name: &str, + payload: Option<&[u8]>, + type_name: Option<&str>, + ) -> Result> { + match type_name { + Some(type_name) => not_impl_err!( + "This decoder cannot decode the self-encoded aggregate function \ + '{name}' (type '{type_name}')" + ), + None => self.decode_udaf(name, payload), + } + } + + /// Reconstruct a window UDF from its name, optional payload and optional + /// self-encoded type name. + fn decode_udwf_definition( + &self, + name: &str, + payload: Option<&[u8]>, + type_name: Option<&str>, + ) -> Result> { + match type_name { + Some(type_name) => not_impl_err!( + "This decoder cannot decode the self-encoded window function \ + '{name}' (type '{type_name}')" + ), + None => self.decode_udwf(name, payload), + } + } } /// Context handed to [`ExecutionPlan::try_to_proto`]. @@ -262,11 +351,24 @@ impl<'a> ExecutionPlanEncodeCtx<'a> { self.encoder.encode_udaf(udaf) } + /// Serialize an aggregate UDF to its payload and decoder type name. Plan + /// nodes with a `fun_type_name` field use this over [`Self::encode_udaf`], + /// so a self-encoded function keeps its state. + pub fn encode_udaf_definition(&self, udaf: &AggregateUDF) -> Result { + self.encoder.encode_udaf_definition(udaf) + } + /// Serialize a window UDF to an opaque payload (`None` = decodable by name). pub fn encode_udwf(&self, udwf: &WindowUDF) -> Result>> { self.encoder.encode_udwf(udwf) } + /// Serialize a window UDF to its payload and decoder type name. See + /// [`Self::encode_udaf_definition`]. + pub fn encode_udwf_definition(&self, udwf: &WindowUDF) -> Result { + self.encoder.encode_udwf_definition(udwf) + } + /// An expression-level encode context backed by this plan context. /// /// Lets a plan hand `ctx` to expression-level conversions that own their own @@ -392,6 +494,18 @@ impl<'a> ExecutionPlanDecodeCtx<'a> { self.decoder.decode_udaf(name, payload) } + /// Reconstruct an aggregate UDF from its name, optional payload and the + /// type name of an [`EncodedFunction`]. + pub fn decode_udaf_definition( + &self, + name: &str, + payload: Option<&[u8]>, + type_name: Option<&str>, + ) -> Result> { + self.decoder + .decode_udaf_definition(name, payload, type_name) + } + /// Reconstruct a window UDF from its name and optional payload. pub fn decode_udwf( &self, @@ -401,6 +515,18 @@ impl<'a> ExecutionPlanDecodeCtx<'a> { self.decoder.decode_udwf(name, payload) } + /// Reconstruct a window UDF from its name, optional payload and the type + /// name of an [`EncodedFunction`]. + pub fn decode_udwf_definition( + &self, + name: &str, + payload: Option<&[u8]>, + type_name: Option<&str>, + ) -> Result> { + self.decoder + .decode_udwf_definition(name, payload, type_name) + } + /// An expression-level decode context backed by this plan context, bound to /// `input_schema`. /// @@ -454,9 +580,124 @@ mod tests { use crate::proto_test_util::{ StubPlanDecoder, StubPlanEncoder, encoded_child_node, stub_child, }; + use arrow::datatypes::{DataType, Field, FieldRef}; + use datafusion_expr::function::AccumulatorArgs; + use datafusion_expr::{ + Accumulator, AggregateUDFImpl, PartitionEvaluator, Signature, Volatility, + WindowUDFImpl, + }; + use datafusion_functions_window_common::field::WindowUDFFieldArgs; + use datafusion_functions_window_common::partition::PartitionEvaluatorArgs; use datafusion_proto_models::protobuf::PhysicalExtensionNode; use datafusion_proto_models::protobuf::physical_plan_node::PhysicalPlanType; + /// An aggregate and window function that writes its own state. + #[derive(Debug, PartialEq, Eq, Hash)] + struct SelfEncoded(Signature); + + impl SelfEncoded { + const NAME: &'static str = "test.SelfEncoded"; + + fn new() -> Self { + Self(Signature::exact( + vec![DataType::Int64], + Volatility::Immutable, + )) + } + + fn state() -> EncodedFunction { + EncodedFunction { + payload: Some(b"state".to_vec()), + type_name: Some(Self::NAME.to_string()), + } + } + } + + impl AggregateUDFImpl for SelfEncoded { + fn name(&self) -> &str { + "self_encoded" + } + fn signature(&self) -> &Signature { + &self.0 + } + fn return_type(&self, _arg_types: &[DataType]) -> Result { + Ok(DataType::Int64) + } + fn accumulator(&self, _args: AccumulatorArgs) -> Result> { + not_impl_err!("test only") + } + fn try_encode_state(&self) -> Result> { + Ok(Some(UDFState { + type_name: Self::NAME, + payload: b"state".to_vec(), + })) + } + } + + impl WindowUDFImpl for SelfEncoded { + fn name(&self) -> &str { + "self_encoded" + } + fn signature(&self) -> &Signature { + &self.0 + } + fn partition_evaluator( + &self, + _args: PartitionEvaluatorArgs, + ) -> Result> { + not_impl_err!("test only") + } + fn field(&self, field_args: WindowUDFFieldArgs) -> Result { + Ok(Field::new(field_args.name(), DataType::Int64, true).into()) + } + fn try_encode_state(&self) -> Result> { + Ok(Some(UDFState { + type_name: Self::NAME, + payload: b"state".to_vec(), + })) + } + } + + /// `StubPlanEncoder` implements the bytes-only methods alone, and they + /// return `None`. The provided definition methods must still carry the + /// state of a self-encoded function. + #[test] + fn provided_definition_encoders_keep_self_encoded_state() -> Result<()> { + let encoder = StubPlanEncoder::ok(); + let ctx = ExecutionPlanEncodeCtx::new(&encoder); + assert_eq!( + ctx.encode_udaf_definition(&AggregateUDF::new_from_impl(SelfEncoded::new()))?, + SelfEncoded::state() + ); + assert_eq!( + ctx.encode_udwf_definition(&WindowUDF::new_from_impl(SelfEncoded::new()))?, + SelfEncoded::state() + ); + Ok(()) + } + + #[test] + fn provided_definition_decoders_reject_a_type_name() { + let decoder = StubPlanDecoder::ok(); + let ctx = ExecutionPlanDecodeCtx::new(&decoder); + let err = ctx + .decode_udaf_definition("f", Some(b"state"), Some(SelfEncoded::NAME)) + .unwrap_err(); + assert_eq!( + err.strip_backtrace(), + "This feature is not implemented: This decoder cannot decode the \ + self-encoded aggregate function 'f' (type 'test.SelfEncoded')" + ); + let err = ctx + .decode_udwf_definition("f", Some(b"state"), Some(SelfEncoded::NAME)) + .unwrap_err(); + assert_eq!( + err.strip_backtrace(), + "This feature is not implemented: This decoder cannot decode the \ + self-encoded window function 'f' (type 'test.SelfEncoded')" + ); + } + /// The wire node a `RegisteredExec` with one child encodes to. fn encode(plan: &RegisteredExec, encoder: &StubPlanEncoder) -> PhysicalExtensionNode { let node = plan diff --git a/datafusion/physical-plan/src/windows/proto.rs b/datafusion/physical-plan/src/windows/proto.rs index c460f0ad6bd97..8e13fe60cfd6f 100644 --- a/datafusion/physical-plan/src/windows/proto.rs +++ b/datafusion/physical-plan/src/windows/proto.rs @@ -36,7 +36,10 @@ pub fn encode_physical_window_expr( let window_frame = window_expr.get_window_frame(); let ( window_function, - fun_definition, + crate::proto::EncodedFunction { + payload: fun_definition, + type_name: fun_type_name, + }, ignore_nulls, distinct, is_reversed, @@ -48,7 +51,7 @@ pub fn encode_physical_window_expr( physical_window_expr_node::WindowFunction::UserDefinedAggrFunction( aggregate_expr.fun().name().to_string(), ), - ctx.encode_udaf(aggregate_expr.fun())?, + ctx.encode_udaf_definition(aggregate_expr.fun())?, aggregate_expr.ignore_nulls(), aggregate_expr.is_distinct(), aggregate_expr.is_reversed(), @@ -61,7 +64,7 @@ pub fn encode_physical_window_expr( physical_window_expr_node::WindowFunction::UserDefinedAggrFunction( aggregate_expr.fun().name().to_string(), ), - ctx.encode_udaf(aggregate_expr.fun())?, + ctx.encode_udaf_definition(aggregate_expr.fun())?, aggregate_expr.ignore_nulls(), aggregate_expr.is_distinct(), aggregate_expr.is_reversed(), @@ -81,7 +84,7 @@ pub fn encode_physical_window_expr( physical_window_expr_node::WindowFunction::UserDefinedWindowFunction( window_udf.fun().name().to_string(), ), - ctx.encode_udwf(window_udf.fun().as_ref())?, + ctx.encode_udwf_definition(window_udf.fun().as_ref())?, window_udf.ignore_nulls(), false, window_udf.is_reversed(), @@ -118,6 +121,7 @@ pub fn encode_physical_window_expr( filter, is_reversed, ordering_req, + fun_type_name, }) } @@ -150,14 +154,18 @@ pub fn decode_physical_window_expr( let function = match proto.window_function.as_ref() { Some(physical_window_expr_node::WindowFunction::UserDefinedAggrFunction( name, - )) => WindowFunctionDefinition::AggregateUDF( - ctx.decode_udaf(name, proto.fun_definition.as_deref())?, - ), + )) => WindowFunctionDefinition::AggregateUDF(ctx.decode_udaf_definition( + name, + proto.fun_definition.as_deref(), + proto.fun_type_name.as_deref(), + )?), Some(physical_window_expr_node::WindowFunction::UserDefinedWindowFunction( name, - )) => WindowFunctionDefinition::WindowUDF( - ctx.decode_udwf(name, proto.fun_definition.as_deref())?, - ), + )) => WindowFunctionDefinition::WindowUDF(ctx.decode_udwf_definition( + name, + proto.fun_definition.as_deref(), + proto.fun_type_name.as_deref(), + )?), None => { return internal_err!("Missing required field 'window_function' in protobuf"); } diff --git a/datafusion/proto-models/proto/datafusion.proto b/datafusion/proto-models/proto/datafusion.proto index 083c371cdb69a..4392d6d3c0f73 100644 --- a/datafusion/proto-models/proto/datafusion.proto +++ b/datafusion/proto-models/proto/datafusion.proto @@ -1104,12 +1104,20 @@ message PhysicalScalarUdfNode { bool nullable = 5; string return_field_name = 6; map return_field_metadata = 7; + // Registry key of the decoder for a function that encoded its own state + // with `ScalarUDFImpl::try_encode_state`. Absent: `fun_definition`, if + // any, belongs to the `PhysicalExtensionCodec`. + optional string fun_type_name = 8; } message PhysicalHigherOrderUdfNode { string name = 1; repeated PhysicalExprNode args = 2; optional bytes fun_definition = 3; + // Registry key of the decoder for a function that encoded its own state + // with `HigherOrderUDFImpl::try_encode_state`. Absent: `fun_definition`, if + // any, belongs to the `PhysicalExtensionCodec`. + optional string fun_type_name = 4; } message PhysicalLambdaExprNode { @@ -1133,6 +1141,10 @@ message PhysicalAggregateExprNode { optional bytes fun_definition = 7; string human_display = 8; bool is_reversed = 9; + // Registry key of the decoder for a function that encoded its own state + // with `AggregateUDFImpl::try_encode_state`. Absent: `fun_definition`, if + // any, belongs to the `PhysicalExtensionCodec`. + optional string fun_type_name = 10; } message PhysicalWindowExprNode { @@ -1152,6 +1164,11 @@ message PhysicalWindowExprNode { PhysicalExprNode filter = 13; bool is_reversed = 14; repeated PhysicalSortExprNode ordering_req = 15; + // Registry key of the decoder for a function that encoded its own state + // with `AggregateUDFImpl::try_encode_state` or + // `WindowUDFImpl::try_encode_state`. Absent: `fun_definition`, if any, + // belongs to the `PhysicalExtensionCodec`. + optional string fun_type_name = 16; } message PhysicalIsNull { diff --git a/datafusion/proto-models/src/generated/pbjson.rs b/datafusion/proto-models/src/generated/pbjson.rs index affbcb8c604ed..a70a7dc0f4f01 100644 --- a/datafusion/proto-models/src/generated/pbjson.rs +++ b/datafusion/proto-models/src/generated/pbjson.rs @@ -19085,6 +19085,9 @@ impl serde::Serialize for PhysicalAggregateExprNode { if self.is_reversed { len += 1; } + if self.fun_type_name.is_some() { + len += 1; + } if self.aggregate_function.is_some() { len += 1; } @@ -19112,6 +19115,9 @@ impl serde::Serialize for PhysicalAggregateExprNode { if self.is_reversed { struct_ser.serialize_field("isReversed", &self.is_reversed)?; } + if let Some(v) = self.fun_type_name.as_ref() { + struct_ser.serialize_field("funTypeName", v)?; + } if let Some(v) = self.aggregate_function.as_ref() { match v { physical_aggregate_expr_node::AggregateFunction::UserDefinedAggrFunction(v) => { @@ -19141,6 +19147,8 @@ impl<'de> serde::Deserialize<'de> for PhysicalAggregateExprNode { "humanDisplay", "is_reversed", "isReversed", + "fun_type_name", + "funTypeName", "user_defined_aggr_function", "userDefinedAggrFunction", ]; @@ -19154,6 +19162,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalAggregateExprNode { FunDefinition, HumanDisplay, IsReversed, + FunTypeName, UserDefinedAggrFunction, } impl<'de> serde::Deserialize<'de> for GeneratedField { @@ -19183,6 +19192,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalAggregateExprNode { "funDefinition" | "fun_definition" => Ok(GeneratedField::FunDefinition), "humanDisplay" | "human_display" => Ok(GeneratedField::HumanDisplay), "isReversed" | "is_reversed" => Ok(GeneratedField::IsReversed), + "funTypeName" | "fun_type_name" => Ok(GeneratedField::FunTypeName), "userDefinedAggrFunction" | "user_defined_aggr_function" => Ok(GeneratedField::UserDefinedAggrFunction), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } @@ -19210,6 +19220,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalAggregateExprNode { let mut fun_definition__ = None; let mut human_display__ = None; let mut is_reversed__ = None; + let mut fun_type_name__ = None; let mut aggregate_function__ = None; while let Some(k) = map_.next_key()? { match k { @@ -19257,6 +19268,12 @@ impl<'de> serde::Deserialize<'de> for PhysicalAggregateExprNode { } is_reversed__ = Some(map_.next_value()?); } + GeneratedField::FunTypeName => { + if fun_type_name__.is_some() { + return Err(serde::de::Error::duplicate_field("funTypeName")); + } + fun_type_name__ = map_.next_value()?; + } GeneratedField::UserDefinedAggrFunction => { if aggregate_function__.is_some() { return Err(serde::de::Error::duplicate_field("userDefinedAggrFunction")); @@ -19273,6 +19290,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalAggregateExprNode { fun_definition: fun_definition__, human_display: human_display__.unwrap_or_default(), is_reversed: is_reversed__.unwrap_or_default(), + fun_type_name: fun_type_name__, aggregate_function: aggregate_function__, }) } @@ -21652,6 +21670,9 @@ impl serde::Serialize for PhysicalHigherOrderUdfNode { if self.fun_definition.is_some() { len += 1; } + if self.fun_type_name.is_some() { + len += 1; + } let mut struct_ser = serializer.serialize_struct("datafusion.PhysicalHigherOrderUdfNode", len)?; if !self.name.is_empty() { struct_ser.serialize_field("name", &self.name)?; @@ -21664,6 +21685,9 @@ impl serde::Serialize for PhysicalHigherOrderUdfNode { #[allow(clippy::needless_borrows_for_generic_args)] struct_ser.serialize_field("funDefinition", pbjson::private::base64::encode(&v).as_str())?; } + if let Some(v) = self.fun_type_name.as_ref() { + struct_ser.serialize_field("funTypeName", v)?; + } struct_ser.end() } } @@ -21678,6 +21702,8 @@ impl<'de> serde::Deserialize<'de> for PhysicalHigherOrderUdfNode { "args", "fun_definition", "funDefinition", + "fun_type_name", + "funTypeName", ]; #[allow(clippy::enum_variant_names)] @@ -21685,6 +21711,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalHigherOrderUdfNode { Name, Args, FunDefinition, + FunTypeName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result @@ -21709,6 +21736,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalHigherOrderUdfNode { "name" => Ok(GeneratedField::Name), "args" => Ok(GeneratedField::Args), "funDefinition" | "fun_definition" => Ok(GeneratedField::FunDefinition), + "funTypeName" | "fun_type_name" => Ok(GeneratedField::FunTypeName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } @@ -21731,6 +21759,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalHigherOrderUdfNode { let mut name__ = None; let mut args__ = None; let mut fun_definition__ = None; + let mut fun_type_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Name => { @@ -21753,12 +21782,19 @@ impl<'de> serde::Deserialize<'de> for PhysicalHigherOrderUdfNode { map_.next_value::<::std::option::Option<::pbjson::private::BytesDeserialize<_>>>()?.map(|x| x.0) ; } + GeneratedField::FunTypeName => { + if fun_type_name__.is_some() { + return Err(serde::de::Error::duplicate_field("funTypeName")); + } + fun_type_name__ = map_.next_value()?; + } } } Ok(PhysicalHigherOrderUdfNode { name: name__.unwrap_or_default(), args: args__.unwrap_or_default(), fun_definition: fun_definition__, + fun_type_name: fun_type_name__, }) } } @@ -23781,6 +23817,9 @@ impl serde::Serialize for PhysicalScalarUdfNode { if !self.return_field_metadata.is_empty() { len += 1; } + if self.fun_type_name.is_some() { + len += 1; + } let mut struct_ser = serializer.serialize_struct("datafusion.PhysicalScalarUdfNode", len)?; if !self.name.is_empty() { struct_ser.serialize_field("name", &self.name)?; @@ -23805,6 +23844,9 @@ impl serde::Serialize for PhysicalScalarUdfNode { if !self.return_field_metadata.is_empty() { struct_ser.serialize_field("returnFieldMetadata", &self.return_field_metadata)?; } + if let Some(v) = self.fun_type_name.as_ref() { + struct_ser.serialize_field("funTypeName", v)?; + } struct_ser.end() } } @@ -23826,6 +23868,8 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode { "returnFieldName", "return_field_metadata", "returnFieldMetadata", + "fun_type_name", + "funTypeName", ]; #[allow(clippy::enum_variant_names)] @@ -23837,6 +23881,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode { Nullable, ReturnFieldName, ReturnFieldMetadata, + FunTypeName, } impl<'de> serde::Deserialize<'de> for GeneratedField { fn deserialize(deserializer: D) -> std::result::Result @@ -23865,6 +23910,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode { "nullable" => Ok(GeneratedField::Nullable), "returnFieldName" | "return_field_name" => Ok(GeneratedField::ReturnFieldName), "returnFieldMetadata" | "return_field_metadata" => Ok(GeneratedField::ReturnFieldMetadata), + "funTypeName" | "fun_type_name" => Ok(GeneratedField::FunTypeName), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), } } @@ -23891,6 +23937,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode { let mut nullable__ = None; let mut return_field_name__ = None; let mut return_field_metadata__ = None; + let mut fun_type_name__ = None; while let Some(k) = map_.next_key()? { match k { GeneratedField::Name => { @@ -23939,6 +23986,12 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode { map_.next_value::>()? ); } + GeneratedField::FunTypeName => { + if fun_type_name__.is_some() { + return Err(serde::de::Error::duplicate_field("funTypeName")); + } + fun_type_name__ = map_.next_value()?; + } } } Ok(PhysicalScalarUdfNode { @@ -23949,6 +24002,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalScalarUdfNode { nullable: nullable__.unwrap_or_default(), return_field_name: return_field_name__.unwrap_or_default(), return_field_metadata: return_field_metadata__.unwrap_or_default(), + fun_type_name: fun_type_name__, }) } } @@ -24542,6 +24596,9 @@ impl serde::Serialize for PhysicalWindowExprNode { if !self.ordering_req.is_empty() { len += 1; } + if self.fun_type_name.is_some() { + len += 1; + } if self.window_function.is_some() { len += 1; } @@ -24581,6 +24638,9 @@ impl serde::Serialize for PhysicalWindowExprNode { if !self.ordering_req.is_empty() { struct_ser.serialize_field("orderingReq", &self.ordering_req)?; } + if let Some(v) = self.fun_type_name.as_ref() { + struct_ser.serialize_field("funTypeName", v)?; + } if let Some(v) = self.window_function.as_ref() { match v { physical_window_expr_node::WindowFunction::UserDefinedAggrFunction(v) => { @@ -24619,6 +24679,8 @@ impl<'de> serde::Deserialize<'de> for PhysicalWindowExprNode { "isReversed", "ordering_req", "orderingReq", + "fun_type_name", + "funTypeName", "user_defined_aggr_function", "userDefinedAggrFunction", "user_defined_window_function", @@ -24638,6 +24700,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalWindowExprNode { Filter, IsReversed, OrderingReq, + FunTypeName, UserDefinedAggrFunction, UserDefinedWindowFunction, } @@ -24672,6 +24735,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalWindowExprNode { "filter" => Ok(GeneratedField::Filter), "isReversed" | "is_reversed" => Ok(GeneratedField::IsReversed), "orderingReq" | "ordering_req" => Ok(GeneratedField::OrderingReq), + "funTypeName" | "fun_type_name" => Ok(GeneratedField::FunTypeName), "userDefinedAggrFunction" | "user_defined_aggr_function" => Ok(GeneratedField::UserDefinedAggrFunction), "userDefinedWindowFunction" | "user_defined_window_function" => Ok(GeneratedField::UserDefinedWindowFunction), _ => Err(serde::de::Error::unknown_field(value, FIELDS)), @@ -24704,6 +24768,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalWindowExprNode { let mut filter__ = None; let mut is_reversed__ = None; let mut ordering_req__ = None; + let mut fun_type_name__ = None; let mut window_function__ = None; while let Some(k) = map_.next_key()? { match k { @@ -24775,6 +24840,12 @@ impl<'de> serde::Deserialize<'de> for PhysicalWindowExprNode { } ordering_req__ = Some(map_.next_value()?); } + GeneratedField::FunTypeName => { + if fun_type_name__.is_some() { + return Err(serde::de::Error::duplicate_field("funTypeName")); + } + fun_type_name__ = map_.next_value()?; + } GeneratedField::UserDefinedAggrFunction => { if window_function__.is_some() { return Err(serde::de::Error::duplicate_field("userDefinedAggrFunction")); @@ -24801,6 +24872,7 @@ impl<'de> serde::Deserialize<'de> for PhysicalWindowExprNode { filter: filter__, is_reversed: is_reversed__.unwrap_or_default(), ordering_req: ordering_req__.unwrap_or_default(), + fun_type_name: fun_type_name__, window_function: window_function__, }) } diff --git a/datafusion/proto-models/src/generated/prost.rs b/datafusion/proto-models/src/generated/prost.rs index 70105f0b51da5..1cb8118a79d27 100644 --- a/datafusion/proto-models/src/generated/prost.rs +++ b/datafusion/proto-models/src/generated/prost.rs @@ -1715,6 +1715,11 @@ pub struct PhysicalScalarUdfNode { ::prost::alloc::string::String, ::prost::alloc::string::String, >, + /// Registry key of the decoder for a function that encoded its own state + /// with `ScalarUDFImpl::try_encode_state`. Absent: `fun_definition`, if + /// any, belongs to the `PhysicalExtensionCodec`. + #[prost(string, optional, tag = "8")] + pub fun_type_name: ::core::option::Option<::prost::alloc::string::String>, } #[derive(Clone, PartialEq, ::prost::Message)] pub struct PhysicalHigherOrderUdfNode { @@ -1724,6 +1729,11 @@ pub struct PhysicalHigherOrderUdfNode { pub args: ::prost::alloc::vec::Vec, #[prost(bytes = "vec", optional, tag = "3")] pub fun_definition: ::core::option::Option<::prost::alloc::vec::Vec>, + /// Registry key of the decoder for a function that encoded its own state + /// with `HigherOrderUDFImpl::try_encode_state`. Absent: `fun_definition`, if + /// any, belongs to the `PhysicalExtensionCodec`. + #[prost(string, optional, tag = "4")] + pub fun_type_name: ::core::option::Option<::prost::alloc::string::String>, } #[derive(Clone, PartialEq, ::prost::Message)] pub struct PhysicalLambdaExprNode { @@ -1755,6 +1765,11 @@ pub struct PhysicalAggregateExprNode { pub human_display: ::prost::alloc::string::String, #[prost(bool, tag = "9")] pub is_reversed: bool, + /// Registry key of the decoder for a function that encoded its own state + /// with `AggregateUDFImpl::try_encode_state`. Absent: `fun_definition`, if + /// any, belongs to the `PhysicalExtensionCodec`. + #[prost(string, optional, tag = "10")] + pub fun_type_name: ::core::option::Option<::prost::alloc::string::String>, #[prost(oneof = "physical_aggregate_expr_node::AggregateFunction", tags = "4")] pub aggregate_function: ::core::option::Option< physical_aggregate_expr_node::AggregateFunction, @@ -1792,6 +1807,12 @@ pub struct PhysicalWindowExprNode { pub is_reversed: bool, #[prost(message, repeated, tag = "15")] pub ordering_req: ::prost::alloc::vec::Vec, + /// Registry key of the decoder for a function that encoded its own state + /// with `AggregateUDFImpl::try_encode_state` or + /// `WindowUDFImpl::try_encode_state`. Absent: `fun_definition`, if any, + /// belongs to the `PhysicalExtensionCodec`. + #[prost(string, optional, tag = "16")] + pub fun_type_name: ::core::option::Option<::prost::alloc::string::String>, #[prost(oneof = "physical_window_expr_node::WindowFunction", tags = "3, 10")] pub window_function: ::core::option::Option< physical_window_expr_node::WindowFunction, diff --git a/datafusion/proto/Cargo.toml b/datafusion/proto/Cargo.toml index a25648d907a56..9fd94886dceaf 100644 --- a/datafusion/proto/Cargo.toml +++ b/datafusion/proto/Cargo.toml @@ -53,7 +53,7 @@ datafusion-datasource-avro = { workspace = true, optional = true, features = ["p datafusion-datasource-csv = { workspace = true, features = ["proto"] } datafusion-datasource-json = { workspace = true, features = ["proto"] } datafusion-datasource-parquet = { workspace = true, optional = true, features = ["proto"] } -datafusion-execution = { workspace = true } +datafusion-execution = { workspace = true, features = ["proto"] } datafusion-expr = { workspace = true, features = ["proto"] } datafusion-functions-table = { workspace = true, features = ["proto"] } datafusion-physical-expr = { workspace = true, features = ["proto"] } diff --git a/datafusion/proto/src/physical_plan/from_proto.rs b/datafusion/proto/src/physical_plan/from_proto.rs index 29a16574f1c65..dc88e9f13b35f 100644 --- a/datafusion/proto/src/physical_plan/from_proto.rs +++ b/datafusion/proto/src/physical_plan/from_proto.rs @@ -14,7 +14,13 @@ use datafusion_common::{DataFusionError, Result, not_impl_err}; use datafusion_datasource::TableSchema; use datafusion_datasource::file::FileSource; use datafusion_datasource::file_scan_config::FileScanConfig; +use datafusion_execution::proto::{ + aggregate_udf_names, decode_aggregate_udf, decode_higher_order_udf, + decode_scalar_udf, decode_window_udf, higher_order_udf_names, scalar_udf_names, + window_udf_names, +}; use datafusion_execution::{FunctionRegistry, TaskContext}; +use datafusion_expr::{AggregateUDF, HigherOrderUDF, ScalarUDF, WindowUDF}; use datafusion_physical_expr::expressions::{LambdaExpr, LambdaVariable}; use datafusion_physical_expr::scalar_subquery::ScalarSubqueryExpr; use datafusion_physical_expr::{ @@ -239,14 +245,21 @@ pub fn parse_physical_expr_with_converter( name, args, fun_definition, + fun_type_name, return_type, nullable, return_field_name, return_field_metadata, } = e; - let udf = match fun_definition { - Some(buf) => ctx.codec().try_decode_udf(name, buf)?, - None => ctx + let udf = match (fun_type_name, fun_definition) { + (Some(type_name), payload) => decode_self_encoded_udf( + ctx.task_ctx(), + name, + type_name, + payload.as_deref().unwrap_or_default(), + )?, + (None, Some(buf)) => ctx.codec().try_decode_udf(name, buf)?, + (None, None) => ctx .task_ctx() .udf(name.as_str()) .or_else(|_| ctx.codec().try_decode_udf(name, &[]))?, @@ -273,11 +286,17 @@ pub fn parse_physical_expr_with_converter( )) } ExprType::HigherOrderUdf(e) => { - let func = match &e.fun_definition { - Some(buf) => { + let func = match (&e.fun_type_name, &e.fun_definition) { + (Some(type_name), payload) => decode_self_encoded_higher_order_udf( + ctx.task_ctx(), + &e.name, + type_name, + payload.as_deref().unwrap_or_default(), + )?, + (None, Some(buf)) => { ctx.codec().try_decode_higher_order_function(&e.name, buf)? } - None => ctx + (None, None) => ctx .task_ctx() .higher_order_function(e.name.as_str()) .or_else(|_| { @@ -510,3 +529,157 @@ impl datafusion_physical_expr_common::physical_expr::proto_decode::PhysicalExprD Some(self.ctx.task_ctx()) } } + +/// Decode a scalar UDF that wrote its own state, with the registry decoder for +/// `type_name`. There is no codec fallback: `fun_type_name` says the codec did +/// not write the payload. +fn decode_self_encoded_udf( + task_ctx: &TaskContext, + name: &str, + type_name: &str, + payload: &[u8], +) -> Result> { + decode_self_encoded( + task_ctx, + SelfEncoded { + kind: "scalar", + trait_name: "ScalarUdfFromProto", + name, + type_name, + payload, + }, + decode_scalar_udf, + |r| scalar_udf_names(r).collect(), + |f| f.name(), + ) +} + +/// Decode an aggregate UDF that wrote its own state. See +/// [`decode_self_encoded_udf`]. +pub(crate) fn decode_self_encoded_udaf( + task_ctx: &TaskContext, + name: &str, + type_name: &str, + payload: &[u8], +) -> Result> { + decode_self_encoded( + task_ctx, + SelfEncoded { + kind: "aggregate", + trait_name: "AggregateUdfFromProto", + name, + type_name, + payload, + }, + decode_aggregate_udf, + |r| aggregate_udf_names(r).collect(), + |f| f.name(), + ) +} + +/// Decode a window UDF that wrote its own state. See +/// [`decode_self_encoded_udf`]. +pub(crate) fn decode_self_encoded_udwf( + task_ctx: &TaskContext, + name: &str, + type_name: &str, + payload: &[u8], +) -> Result> { + decode_self_encoded( + task_ctx, + SelfEncoded { + kind: "window", + trait_name: "WindowUdfFromProto", + name, + type_name, + payload, + }, + decode_window_udf, + |r| window_udf_names(r).collect(), + |f| f.name(), + ) +} + +/// Decode a higher-order function that wrote its own state. See +/// [`decode_self_encoded_udf`]. +fn decode_self_encoded_higher_order_udf( + task_ctx: &TaskContext, + name: &str, + type_name: &str, + payload: &[u8], +) -> Result> { + decode_self_encoded( + task_ctx, + SelfEncoded { + kind: "higher-order", + trait_name: "HigherOrderUdfFromProto", + name, + type_name, + payload, + }, + decode_higher_order_udf, + |r| higher_order_udf_names(r).collect(), + |f| f.name(), + ) +} + +/// What the wire says about one self-encoded function. +#[derive(Clone, Copy)] +struct SelfEncoded<'a> { + /// The function kind, for error messages. + kind: &'static str, + /// The decoder trait to register, for error messages. + trait_name: &'static str, + name: &'a str, + type_name: &'a str, + payload: &'a [u8], +} + +type RegistryDecodeFn = + fn(&ProtoDecoderRegistry, &str, &[u8], &str, &TaskContext) -> Option>>; + +fn decode_self_encoded( + task_ctx: &TaskContext, + wire: SelfEncoded<'_>, + decode: RegistryDecodeFn, + names: impl for<'r> Fn(&'r ProtoDecoderRegistry) -> Vec<&'r str>, + fun_name: impl Fn(&F) -> &str, +) -> Result> { + let SelfEncoded { + kind, + trait_name, + name, + type_name, + payload, + } = wire; + let registry = task_ctx + .session_config() + .get_extension::(); + if let Some(decoded) = registry + .as_deref() + .and_then(|r| decode(r, type_name, payload, name, task_ctx)) + { + let fun = decoded?; + if fun_name(&fun) != name { + return Err(proto_error(format!( + "Decoder for {kind} function type '{type_name}' returned a function \ + named '{}', expected '{name}'", + fun_name(&fun) + ))); + } + return Ok(fun); + } + let mut registered: Vec<&str> = registry.as_deref().map(names).unwrap_or_default(); + registered.sort_unstable(); + let registered = if registered.is_empty() { + "none".to_string() + } else { + registered.join(", ") + }; + Err(proto_error(format!( + "No decoder is registered for the {kind} function type '{type_name}' \ + (function '{name}'). Register it with `{trait_name}::register_proto` in the \ + ProtoDecoderRegistry attached to the decoding session's SessionConfig. \ + Registered {kind} function types: {registered}" + ))) +} diff --git a/datafusion/proto/src/physical_plan/mod.rs b/datafusion/proto/src/physical_plan/mod.rs index 36cd8f1c993ed..96b11b4042ade 100644 --- a/datafusion/proto/src/physical_plan/mod.rs +++ b/datafusion/proto/src/physical_plan/mod.rs @@ -622,14 +622,17 @@ mod tests { use datafusion_expr::function::AccumulatorArgs; use datafusion_expr::{ Accumulator, AggregateUDFImpl, ColumnarValue, PartitionEvaluator, - ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, WindowUDFImpl, + ScalarFunctionArgs, ScalarUDFImpl, Signature, UDFState, Volatility, + WindowUDFImpl, }; use datafusion_functions_window_common::field::WindowUDFFieldArgs; use datafusion_functions_window_common::partition::PartitionEvaluatorArgs; + use datafusion_physical_plan::proto::EncodedFunction; #[derive(Debug, PartialEq, Eq, Hash)] struct TestUdf { signature: Signature, + self_encoded: bool, } impl TestUdf { @@ -639,6 +642,15 @@ mod tests { vec![DataType::Int64], Volatility::Immutable, ), + self_encoded: false, + } + } + + /// An instance that writes its own state. + fn self_encoded() -> Self { + Self { + self_encoded: true, + ..Self::new() } } } @@ -647,6 +659,12 @@ mod tests { fn name(&self) -> &str { "test_udf" } + fn try_encode_state(&self) -> Result> { + Ok(self.self_encoded.then(|| UDFState { + type_name: "test.TestUdf", + payload: b"state".to_vec(), + })) + } fn signature(&self) -> &Signature { &self.signature } @@ -664,6 +682,7 @@ mod tests { #[derive(Debug, PartialEq, Eq, Hash)] struct TestUdaf { signature: Signature, + self_encoded: bool, } impl TestUdaf { @@ -673,6 +692,15 @@ mod tests { vec![DataType::Int64], Volatility::Immutable, ), + self_encoded: false, + } + } + + /// An instance that writes its own state. + fn self_encoded() -> Self { + Self { + self_encoded: true, + ..Self::new() } } } @@ -681,6 +709,12 @@ mod tests { fn name(&self) -> &str { "test_udaf" } + fn try_encode_state(&self) -> Result> { + Ok(self.self_encoded.then(|| UDFState { + type_name: "test.TestUdaf", + payload: b"state".to_vec(), + })) + } fn signature(&self) -> &Signature { &self.signature } @@ -698,6 +732,7 @@ mod tests { #[derive(Debug, PartialEq, Eq, Hash)] struct TestUdwf { signature: Signature, + self_encoded: bool, } impl TestUdwf { @@ -707,6 +742,15 @@ mod tests { vec![DataType::Int64], Volatility::Immutable, ), + self_encoded: false, + } + } + + /// An instance that writes its own state. + fn self_encoded() -> Self { + Self { + self_encoded: true, + ..Self::new() } } } @@ -715,6 +759,12 @@ mod tests { fn name(&self) -> &str { "test_udwf" } + fn try_encode_state(&self) -> Result> { + Ok(self.self_encoded.then(|| UDFState { + type_name: "test.TestUdwf", + payload: b"state".to_vec(), + })) + } fn signature(&self) -> &Signature { &self.signature } @@ -895,6 +945,85 @@ mod tests { Ok(()) } + /// `PayloadCodec` writes bytes for every function. A function's own + /// state must win over those bytes, and a channel with no slot for the + /// type name must fail instead of dropping the state. + #[test] + fn bytes_only_encoders_reject_self_encoded_functions() { + let codec = PayloadCodec; + let converter = DefaultPhysicalProtoConverter {}; + let encoder = encode_ctx_over(&codec, &converter); + let ctx = ExecutionPlanEncodeCtx::new(&encoder); + + let err = ctx + .encode_udf(&ScalarUDF::from(TestUdf::self_encoded())) + .unwrap_err(); + assert_eq!( + err.strip_backtrace(), + "This feature is not implemented: Scalar function 'test_udf' (type \ + 'test.TestUdf') encodes its own state, which this plan node cannot \ + carry" + ); + let err = ctx + .encode_udaf(&AggregateUDF::from(TestUdaf::self_encoded())) + .unwrap_err(); + assert_eq!( + err.strip_backtrace(), + "This feature is not implemented: Aggregate function 'test_udaf' (type \ + 'test.TestUdaf') encodes its own state, which this plan node cannot \ + carry. Use `encode_udaf_definition`" + ); + let err = ctx + .encode_udwf(&WindowUDF::from(TestUdwf::self_encoded())) + .unwrap_err(); + assert_eq!( + err.strip_backtrace(), + "This feature is not implemented: Window function 'test_udwf' (type \ + 'test.TestUdwf') encodes its own state, which this plan node cannot \ + carry. Use `encode_udwf_definition`" + ); + } + + #[test] + fn definition_encoders_prefer_function_state_over_codec() -> Result<()> { + let codec = PayloadCodec; + let converter = DefaultPhysicalProtoConverter {}; + let encoder = encode_ctx_over(&codec, &converter); + let ctx = ExecutionPlanEncodeCtx::new(&encoder); + + assert_eq!( + ctx.encode_udaf_definition( + &AggregateUDF::from(TestUdaf::self_encoded()) + )?, + EncodedFunction { + payload: Some(b"state".to_vec()), + type_name: Some("test.TestUdaf".to_string()), + } + ); + assert_eq!( + ctx.encode_udwf_definition(&WindowUDF::from(TestUdwf::self_encoded()))?, + EncodedFunction { + payload: Some(b"state".to_vec()), + type_name: Some("test.TestUdwf".to_string()), + } + ); + assert_eq!( + ctx.encode_udaf_definition(&AggregateUDF::from(TestUdaf::new()))?, + EncodedFunction { + payload: Some(b"test_udaf".to_vec()), + type_name: None, + } + ); + assert_eq!( + ctx.encode_udwf_definition(&WindowUDF::from(TestUdwf::new()))?, + EncodedFunction { + payload: Some(b"test_udwf".to_vec()), + type_name: None, + } + ); + Ok(()) + } + #[test] fn decode_functions_prefer_explicit_payload() -> Result<()> { let task_ctx = TaskContext::default(); @@ -2017,21 +2146,39 @@ impl ExecutionPlanEncode for ConverterPlanEncoder<'_> { // Bytes-only function serde. `(!buf.is_empty()).then_some(buf)` preserves the // existing `fun_definition` wire semantics (empty payload == encode-by-name). fn encode_udf(&self, udf: &ScalarUDF) -> Result>> { - let mut buf = vec![]; - self.codec.try_encode_udf(udf, &mut buf)?; - Ok((!buf.is_empty()).then_some(buf)) + // This bytes-only channel has no slot for `fun_type_name`, so a + // self-encoding UDF cannot travel through it. Fail rather than let + // the decoder fall back to a by-name lookup. + match to_proto::encode_scalar_udf(udf, self.codec)? { + (_, Some(type_name)) => not_impl_err!( + "Scalar function '{}' (type '{type_name}') encodes its own state, \ + which this plan node cannot carry", + udf.name() + ), + (buf, None) => Ok(buf), + } } fn encode_udaf(&self, udaf: &AggregateUDF) -> Result>> { - let mut buf = vec![]; - self.codec.try_encode_udaf(udaf, &mut buf)?; - Ok((!buf.is_empty()).then_some(buf)) + match to_proto::encode_aggregate_udf(udaf, self.codec)? { + (_, Some(type_name)) => not_impl_err!( + "Aggregate function '{}' (type '{type_name}') encodes its own state, \ + which this plan node cannot carry. Use `encode_udaf_definition`", + udaf.name() + ), + (buf, None) => Ok(buf), + } } fn encode_udwf(&self, udwf: &WindowUDF) -> Result>> { - let mut buf = vec![]; - self.codec.try_encode_udwf(udwf, &mut buf)?; - Ok((!buf.is_empty()).then_some(buf)) + match to_proto::encode_window_udf(udwf, self.codec)? { + (_, Some(type_name)) => not_impl_err!( + "Window function '{}' (type '{type_name}') encodes its own state, \ + which this plan node cannot carry. Use `encode_udwf_definition`", + udwf.name() + ), + (buf, None) => Ok(buf), + } } } @@ -2104,6 +2251,23 @@ impl ExecutionPlanDecode for ConverterPlanDecoder<'_, '_> { } } + fn decode_udaf_definition( + &self, + name: &str, + payload: Option<&[u8]>, + type_name: Option<&str>, + ) -> Result> { + match type_name { + Some(type_name) => from_proto::decode_self_encoded_udaf( + self.ctx.task_ctx(), + name, + type_name, + payload.unwrap_or_default(), + ), + None => self.decode_udaf(name, payload), + } + } + fn decode_udwf(&self, name: &str, payload: Option<&[u8]>) -> Result> { match payload { Some(buf) => self.ctx.codec().try_decode_udwf(name, buf), @@ -2114,6 +2278,23 @@ impl ExecutionPlanDecode for ConverterPlanDecoder<'_, '_> { .or_else(|_| self.ctx.codec().try_decode_udwf(name, &[])), } } + + fn decode_udwf_definition( + &self, + name: &str, + payload: Option<&[u8]>, + type_name: Option<&str>, + ) -> Result> { + match type_name { + Some(type_name) => from_proto::decode_self_encoded_udwf( + self.ctx.task_ctx(), + name, + type_name, + payload.unwrap_or_default(), + ), + None => self.decode_udwf(name, payload), + } + } } /// Borrow a required message field, or fail with a protobuf error naming it. diff --git a/datafusion/proto/src/physical_plan/to_proto.rs b/datafusion/proto/src/physical_plan/to_proto.rs index c5ead642886f2..01ef48ec89d89 100644 --- a/datafusion/proto/src/physical_plan/to_proto.rs +++ b/datafusion/proto/src/physical_plan/to_proto.rs @@ -37,8 +37,7 @@ pub fn serialize_physical_aggr_expr( )?; let name = aggr_expr.fun().name().to_string(); - let mut buf = Vec::new(); - codec.try_encode_udaf(aggr_expr.fun(), &mut buf)?; + let (fun_definition, fun_type_name) = encode_aggregate_udf(aggr_expr.fun(), codec)?; let human_display = match (aggr_expr.human_display(), aggr_expr.human_display_alias()) { (Some(display), Some(alias)) => encode_human_display_alias(display, alias), @@ -54,9 +53,10 @@ pub fn serialize_physical_aggr_expr( ordering_req: order_bys, distinct: aggr_expr.is_distinct(), ignore_nulls: aggr_expr.ignore_nulls(), - fun_definition: (!buf.is_empty()).then_some(buf), + fun_definition, human_display, is_reversed: aggr_expr.is_reversed(), + fun_type_name, }, )), }) @@ -192,8 +192,7 @@ pub fn serialize_physical_expr_with_converter( } if let Some(expr) = expr.downcast_ref::() { - let mut buf = Vec::new(); - codec.try_encode_udf(expr.fun(), &mut buf)?; + let (fun_definition, fun_type_name) = encode_scalar_udf(expr.fun(), codec)?; let return_field = expr.return_field(&Schema::empty())?; Ok(protobuf::PhysicalExprNode { expr_id, @@ -201,7 +200,8 @@ pub fn serialize_physical_expr_with_converter( protobuf::PhysicalScalarUdfNode { name: expr.name().to_string(), args: serialize_physical_exprs(expr.args(), codec, proto_converter)?, - fun_definition: (!buf.is_empty()).then_some(buf), + fun_definition, + fun_type_name, return_type: Some(return_field.data_type().try_into()?), nullable: return_field.is_nullable(), return_field_name: return_field.name().to_string(), @@ -210,15 +210,15 @@ pub fn serialize_physical_expr_with_converter( )), }) } else if let Some(expr) = expr.downcast_ref::() { - let mut buf = Vec::new(); - codec.try_encode_higher_order_function(expr.fun(), &mut buf)?; + let (fun_definition, fun_type_name) = encode_higher_order_udf(expr.fun(), codec)?; Ok(protobuf::PhysicalExprNode { expr_id, expr_type: Some(protobuf::physical_expr_node::ExprType::HigherOrderUdf( protobuf::PhysicalHigherOrderUdfNode { name: expr.name().to_string(), args: serialize_physical_exprs(expr.args(), codec, proto_converter)?, - fun_definition: (!buf.is_empty()).then_some(buf), + fun_definition, + fun_type_name, }, )), }) @@ -309,3 +309,66 @@ pub fn serialize_record_batches(batches: &[RecordBatch]) -> Result> { writer.finish()?; Ok(buf) } + +/// Encode a scalar UDF's definition as `(fun_definition, fun_type_name)`. +/// +/// The function's own [`ScalarUDFImpl::try_encode_state`] wins over the +/// codec, as the extension expression and plan registries do. Its payload is +/// kept even when empty, because `fun_type_name` says who wrote it. Codec +/// bytes keep the old wire semantics: empty means "by name". +/// +/// [`ScalarUDFImpl::try_encode_state`]: datafusion_expr::ScalarUDFImpl::try_encode_state +pub(crate) fn encode_scalar_udf( + fun: &datafusion_expr::ScalarUDF, + codec: &dyn PhysicalExtensionCodec, +) -> Result<(Option>, Option)> { + if let Some(state) = fun.try_encode_state()? { + return Ok((Some(state.payload), Some(state.type_name.to_string()))); + } + let mut buf = Vec::new(); + codec.try_encode_udf(fun, &mut buf)?; + Ok(((!buf.is_empty()).then_some(buf), None)) +} + +/// Encode an aggregate UDF's definition as `(fun_definition, fun_type_name)`, +/// with the precedence of [`encode_scalar_udf`]. +pub(crate) fn encode_aggregate_udf( + fun: &datafusion_expr::AggregateUDF, + codec: &dyn PhysicalExtensionCodec, +) -> Result<(Option>, Option)> { + if let Some(state) = fun.try_encode_state()? { + return Ok((Some(state.payload), Some(state.type_name.to_string()))); + } + let mut buf = Vec::new(); + codec.try_encode_udaf(fun, &mut buf)?; + Ok(((!buf.is_empty()).then_some(buf), None)) +} + +/// Encode a window UDF's definition as `(fun_definition, fun_type_name)`, +/// with the precedence of [`encode_scalar_udf`]. +pub(crate) fn encode_window_udf( + fun: &datafusion_expr::WindowUDF, + codec: &dyn PhysicalExtensionCodec, +) -> Result<(Option>, Option)> { + if let Some(state) = fun.try_encode_state()? { + return Ok((Some(state.payload), Some(state.type_name.to_string()))); + } + let mut buf = Vec::new(); + codec.try_encode_udwf(fun, &mut buf)?; + Ok(((!buf.is_empty()).then_some(buf), None)) +} + +/// Encode a higher-order function's definition as +/// `(fun_definition, fun_type_name)`, with the precedence of +/// [`encode_scalar_udf`]. +pub(crate) fn encode_higher_order_udf( + fun: &datafusion_expr::HigherOrderUDF, + codec: &dyn PhysicalExtensionCodec, +) -> Result<(Option>, Option)> { + if let Some(state) = fun.try_encode_state()? { + return Ok((Some(state.payload), Some(state.type_name.to_string()))); + } + let mut buf = Vec::new(); + codec.try_encode_higher_order_function(fun, &mut buf)?; + Ok(((!buf.is_empty()).then_some(buf), None)) +} diff --git a/datafusion/proto/tests/cases/plans/hof_registry.rs b/datafusion/proto/tests/cases/plans/hof_registry.rs new file mode 100644 index 0000000000000..17596b5bdcf8e --- /dev/null +++ b/datafusion/proto/tests/cases/plans/hof_registry.rs @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Stateful higher-order functions decoded through a `ProtoDecoderRegistry` +//! instead of a `PhysicalExtensionCodec`. + +use std::any::Any; +use std::sync::Arc; + +use arrow::array::{Array, Int64Array, ListArray}; +use arrow::datatypes::{DataType, FieldRef}; +use datafusion::execution::TaskContext; +use datafusion::functions_nested::array_transform::ArrayTransform; +use datafusion::physical_plan::projection::ProjectionExec; +use datafusion::physical_plan::{ExecutionPlan, collect}; +use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_common::{Result, internal_err}; +use datafusion_execution::proto::HigherOrderUdfFromProto; +use datafusion_expr::{ + ColumnarValue, HigherOrderFunctionArgs, HigherOrderReturnFieldArgs, + HigherOrderSignature, HigherOrderUDF, HigherOrderUDFImpl, LambdaParametersProgress, + UDFState, ValueOrLambda, +}; +use datafusion_physical_expr::HigherOrderFunctionExpr; +use datafusion_proto::bytes::{ + physical_plan_from_bytes, physical_plan_from_bytes_with_extension_codec, + physical_plan_to_bytes, physical_plan_to_bytes_with_extension_codec, +}; +use datafusion_proto::physical_plan::to_proto::serialize_physical_expr; +use datafusion_proto::physical_plan::{ + DefaultPhysicalExtensionCodec, PhysicalExtensionCodec, +}; +use datafusion_proto::protobuf::PhysicalHigherOrderUdfNode; +use datafusion_proto::protobuf::physical_expr_node::ExprType; + +/// `array_transform` under another SQL name, carrying a `tag` that only the +/// wire can restore. One type, many SQL names. +#[derive(Debug, PartialEq, Eq, Hash)] +struct TaggedTransform { + name: String, + tag: i64, + inner: ArrayTransform, +} + +impl TaggedTransform { + fn new(name: &str, tag: i64) -> Self { + Self { + name: name.to_string(), + tag, + inner: ArrayTransform::new(), + } + } +} + +impl HigherOrderUDFImpl for TaggedTransform { + fn name(&self) -> &str { + &self.name + } + + fn signature(&self) -> &HigherOrderSignature { + self.inner.signature() + } + + fn coerce_value_types(&self, arg_types: &[DataType]) -> Result> { + self.inner.coerce_value_types(arg_types) + } + + fn lambda_parameters( + &self, + step: usize, + fields: &[ValueOrLambda>], + ) -> Result { + self.inner.lambda_parameters(step, fields) + } + + fn return_field_from_args( + &self, + args: HigherOrderReturnFieldArgs, + ) -> Result { + self.inner.return_field_from_args(args) + } + + fn invoke_with_args(&self, args: HigherOrderFunctionArgs) -> Result { + self.inner.invoke_with_args(args) + } + + fn try_encode_state(&self) -> Result> { + Ok(Some(UDFState { + type_name: Self::NAME, + payload: self.tag.to_le_bytes().to_vec(), + })) + } +} + +impl HigherOrderUdfFromProto for TaggedTransform { + const NAME: &'static str = "datafusion.tests.TaggedTransform"; + + fn try_from_proto( + payload: &[u8], + name: &str, + _ctx: &TaskContext, + ) -> Result> { + let tag = i64::from_le_bytes(payload.try_into().unwrap()); + Ok(Arc::new(HigherOrderUDF::new_from_impl( + TaggedTransform::new(name, tag), + ))) + } +} + +/// An unrelated decoder, so the registry is not empty. +struct OtherHof; +impl HigherOrderUdfFromProto for OtherHof { + const NAME: &'static str = "datafusion.tests.OtherHof"; + fn try_from_proto( + _payload: &[u8], + _name: &str, + _ctx: &TaskContext, + ) -> Result> { + internal_err!("unused") + } +} + +/// Plan `SELECT (a, x -> x * 2)` over one row `[1, 2, 3]`, with `hof` +/// registered in the planning session only. +async fn plan(hof: HigherOrderUDF) -> Result> { + // The default dialect does not parse lambdas. + let ctx = SessionContext::new_with_config( + SessionConfig::new().set_str("datafusion.sql_parser.dialect", "duckdb"), + ); + let name = hof.name().to_string(); + ctx.register_higher_order_function(Arc::new(hof)); + ctx.sql(&format!( + "SELECT {name}(a, x -> x * 2) AS y FROM (VALUES (make_array(1, 2, 3))) t(a)" + )) + .await? + .create_physical_plan() + .await +} + +/// The one higher-order function call in `plan`. +fn hof_expr( + plan: &Arc, +) -> Arc { + let projection = plan + .as_ref() + .downcast_ref::() + .expect("expected ProjectionExec"); + let expr = Arc::clone(&projection.expr()[0].expr); + assert!( + expr.downcast_ref::().is_some(), + "{expr:?}" + ); + expr +} + +fn hof_node( + plan: &Arc, + codec: &dyn PhysicalExtensionCodec, +) -> Result { + let node = serialize_physical_expr(&hof_expr(plan), codec)?; + let Some(ExprType::HigherOrderUdf(node)) = node.expr_type else { + panic!("expected PhysicalHigherOrderUdfNode"); + }; + Ok(node) +} + +fn decoded_tag(plan: &Arc) -> Option { + let expr = hof_expr(plan); + let hof = expr + .as_ref() + .downcast_ref::() + .unwrap() + .fun(); + let inner: &dyn Any = hof.inner().as_ref(); + inner.downcast_ref::().map(|t| t.tag) +} + +fn registry_session() -> Result { + let mut config = SessionConfig::new(); + config.update_extension(TaggedTransform::register_proto)?; + config.update_extension(OtherHof::register_proto)?; + Ok(SessionContext::new_with_config(config)) +} + +async fn run(plan: Arc, ctx: &SessionContext) -> Result> { + let batches = collect(plan, ctx.task_ctx()).await?; + assert_eq!(batches.len(), 1); + let list = batches[0] + .column(0) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(list.len(), 1); + let values = list.value(0); + Ok(values + .as_any() + .downcast_ref::() + .unwrap() + .values() + .to_vec()) +} + +#[tokio::test] +async fn stateful_hof_round_trips_in_projection() -> Result<()> { + let plan = plan(HigherOrderUDF::new_from_impl(TaggedTransform::new( + "tagged_7", 7, + ))) + .await?; + let node = hof_node(&plan, &DefaultPhysicalExtensionCodec {})?; + assert_eq!( + (node.fun_type_name.as_deref(), node.fun_definition), + ( + Some(TaggedTransform::NAME), + Some(7i64.to_le_bytes().to_vec()) + ) + ); + + let bytes = physical_plan_to_bytes(plan)?; + let ctx = registry_session()?; + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!(decoded_tag(&decoded), Some(7)); + assert_eq!(run(decoded, &ctx).await?, vec![2, 4, 6]); + Ok(()) +} + +#[tokio::test] +async fn aliased_stateful_hof_round_trips() -> Result<()> { + let hof = HigherOrderUDF::new_from_impl(TaggedTransform::new("tagged_5", 5)) + .with_aliases(["t5"]); + let bytes = physical_plan_to_bytes(plan(hof).await?)?; + let ctx = registry_session()?; + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!(decoded_tag(&decoded), Some(5)); + Ok(()) +} + +#[tokio::test] +async fn unregistered_type_name_errors() -> Result<()> { + let plan = plan(HigherOrderUDF::new_from_impl(TaggedTransform::new( + "tagged_7", 7, + ))) + .await?; + let bytes = physical_plan_to_bytes(plan)?; + let mut config = SessionConfig::new(); + config.update_extension(OtherHof::register_proto)?; + let ctx = SessionContext::new_with_config(config); + let err = physical_plan_from_bytes(&bytes, &ctx.task_ctx()).unwrap_err(); + assert!( + err.to_string().contains( + "No decoder is registered for the higher-order function type \ + 'datafusion.tests.TaggedTransform' (function 'tagged_7'). Register it with \ + `HigherOrderUdfFromProto::register_proto`" + ), + "{err}" + ); + assert!( + err.to_string().contains( + "Registered higher-order function types: datafusion.tests.OtherHof" + ), + "{err}" + ); + Ok(()) +} + +#[tokio::test] +async fn stateless_hof_round_trips_by_name() -> Result<()> { + let plan = plan(HigherOrderUDF::new_from_impl(ArrayTransform::new())).await?; + let node = hof_node(&plan, &DefaultPhysicalExtensionCodec {})?; + assert_eq!((node.fun_definition, node.fun_type_name), (None, None)); + + let bytes = physical_plan_to_bytes(plan)?; + let ctx = SessionContext::new(); + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!(run(decoded, &ctx).await?, vec![2, 4, 6]); + Ok(()) +} + +/// A codec that writes `fun_definition` itself. +#[derive(Debug)] +struct TagCodec; +impl PhysicalExtensionCodec for TagCodec { + fn try_decode( + &self, + _buf: &[u8], + _inputs: &[Arc], + _ctx: &TaskContext, + _proto_converter: &dyn datafusion_proto::physical_plan::PhysicalProtoConverterExtension, + ) -> Result> { + internal_err!("unused") + } + + fn try_encode( + &self, + _node: Arc, + _buf: &mut Vec, + _proto_converter: &dyn datafusion_proto::physical_plan::PhysicalProtoConverterExtension, + ) -> Result<()> { + internal_err!("unused") + } + + fn try_encode_higher_order_function( + &self, + node: &HigherOrderUDF, + buf: &mut Vec, + ) -> Result<()> { + if node.name() == "codec_tagged" { + buf.extend_from_slice(&11i64.to_le_bytes()); + } + Ok(()) + } + + fn try_decode_higher_order_function( + &self, + name: &str, + buf: &[u8], + ) -> Result> { + let tag = i64::from_le_bytes(buf.try_into().unwrap()); + Ok(Arc::new(HigherOrderUDF::new_from_impl(CodecTagged( + TaggedTransform::new(name, tag), + )))) + } +} + +/// Like `TaggedTransform`, but with no `try_encode_state`: only the codec +/// knows it. +#[derive(Debug, PartialEq, Eq, Hash)] +struct CodecTagged(TaggedTransform); +impl HigherOrderUDFImpl for CodecTagged { + fn name(&self) -> &str { + self.0.name() + } + fn signature(&self) -> &HigherOrderSignature { + self.0.signature() + } + fn coerce_value_types(&self, arg_types: &[DataType]) -> Result> { + self.0.coerce_value_types(arg_types) + } + fn lambda_parameters( + &self, + step: usize, + fields: &[ValueOrLambda>], + ) -> Result { + self.0.lambda_parameters(step, fields) + } + fn return_field_from_args( + &self, + args: HigherOrderReturnFieldArgs, + ) -> Result { + self.0.return_field_from_args(args) + } + fn invoke_with_args(&self, args: HigherOrderFunctionArgs) -> Result { + self.0.invoke_with_args(args) + } +} + +#[tokio::test] +async fn codec_written_definition_still_uses_codec() -> Result<()> { + let plan = plan(HigherOrderUDF::new_from_impl(CodecTagged( + TaggedTransform::new("codec_tagged", 11), + ))) + .await?; + let node = hof_node(&plan, &TagCodec)?; + assert_eq!( + (node.fun_definition, node.fun_type_name), + (Some(11i64.to_le_bytes().to_vec()), None) + ); + + let bytes = physical_plan_to_bytes_with_extension_codec(plan, &TagCodec)?; + let ctx = registry_session()?; + let decoded = physical_plan_from_bytes_with_extension_codec( + &bytes, + &ctx.task_ctx(), + &TagCodec, + )?; + let expr = hof_expr(&decoded); + let hof = expr + .as_ref() + .downcast_ref::() + .unwrap() + .fun(); + let inner: &dyn Any = hof.inner().as_ref(); + assert_eq!( + inner.downcast_ref::().map(|t| t.0.tag), + Some(11) + ); + assert_eq!(run(decoded, &ctx).await?, vec![2, 4, 6]); + Ok(()) +} diff --git a/datafusion/proto/tests/cases/plans/mod.rs b/datafusion/proto/tests/cases/plans/mod.rs index 71887fb955420..7f649b5268216 100644 --- a/datafusion/proto/tests/cases/plans/mod.rs +++ b/datafusion/proto/tests/cases/plans/mod.rs @@ -30,6 +30,7 @@ mod expr_registry; mod exprs; mod extensions; mod filters; +mod hof_registry; mod joins; mod lazy_memory; mod leaves; @@ -40,7 +41,10 @@ mod sinks; mod sorts; mod sources; mod tpch; +mod udaf_registry; +mod udf_registry; mod udfs; +mod udwf_registry; mod windows; /// Perform a serde roundtrip and assert that the string representation of the before and after plans diff --git a/datafusion/proto/tests/cases/plans/udaf_registry.rs b/datafusion/proto/tests/cases/plans/udaf_registry.rs new file mode 100644 index 0000000000000..8ab707c3b42ad --- /dev/null +++ b/datafusion/proto/tests/cases/plans/udaf_registry.rs @@ -0,0 +1,424 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Stateful aggregate UDFs decoded through a `ProtoDecoderRegistry` instead of +//! a `PhysicalExtensionCodec`. + +use std::sync::Arc; + +use arrow::array::{Array, ArrayRef, Int64Array}; +use arrow::datatypes::{DataType, Field, Schema}; +use arrow::record_batch::RecordBatch; +use datafusion::datasource::memory::MemorySourceConfig; +use datafusion::execution::TaskContext; +use datafusion::physical_expr::aggregate::{AggregateExprBuilder, AggregateFunctionExpr}; +use datafusion::physical_plan::aggregates::{ + AggregateExec, AggregateMode, PhysicalGroupBy, +}; +use datafusion::physical_plan::expressions::col; +use datafusion::physical_plan::windows::{PlainAggregateWindowExpr, WindowAggExec}; +use datafusion::physical_plan::{ExecutionPlan, collect}; +use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_common::{Result, ScalarValue, internal_err}; +use datafusion_execution::proto::AggregateUdfFromProto; +use datafusion_expr::function::AccumulatorArgs; +use datafusion_expr::{ + Accumulator, AggregateUDF, AggregateUDFImpl, Signature, UDFState, Volatility, + WindowFrame, +}; +use datafusion_functions_aggregate::sum::sum_udaf; +use datafusion_proto::bytes::{ + physical_plan_from_bytes, physical_plan_from_bytes_with_extension_codec, + physical_plan_to_bytes, physical_plan_to_bytes_with_extension_codec, +}; +use datafusion_proto::physical_plan::{ + AsExecutionPlan, DefaultPhysicalExtensionCodec, PhysicalExtensionCodec, +}; +use datafusion_proto::protobuf::physical_expr_node::ExprType; +use datafusion_proto::protobuf::physical_plan_node::PhysicalPlanType; +use datafusion_proto::protobuf::{PhysicalAggregateExprNode, PhysicalPlanNode}; + +/// `sum_scaled(x)` sums `x * factor`. One type, many SQL names. +#[derive(Debug, PartialEq, Eq, Hash)] +struct SumScaled { + name: String, + factor: i64, + signature: Signature, +} + +impl SumScaled { + fn new(name: &str, factor: i64) -> Self { + Self { + name: name.to_string(), + factor, + signature: Signature::exact(vec![DataType::Int64], Volatility::Immutable), + } + } +} + +impl AggregateUDFImpl for SumScaled { + fn name(&self) -> &str { + &self.name + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result { + Ok(DataType::Int64) + } + + fn accumulator(&self, _args: AccumulatorArgs) -> Result> { + Ok(Box::new(SumScaledAcc { + factor: self.factor, + sum: 0, + })) + } + + fn try_encode_state(&self) -> Result> { + Ok(Some(UDFState { + type_name: Self::NAME, + payload: self.factor.to_le_bytes().to_vec(), + })) + } +} + +impl AggregateUdfFromProto for SumScaled { + const NAME: &'static str = "datafusion.tests.SumScaled"; + + fn try_from_proto( + payload: &[u8], + name: &str, + _ctx: &TaskContext, + ) -> Result> { + let factor = i64::from_le_bytes(payload.try_into().unwrap()); + Ok(Arc::new(AggregateUDF::new_from_impl(SumScaled::new( + name, factor, + )))) + } +} + +#[derive(Debug)] +struct SumScaledAcc { + factor: i64, + sum: i64, +} + +impl Accumulator for SumScaledAcc { + fn update_batch(&mut self, values: &[ArrayRef]) -> Result<()> { + let values = values[0].as_any().downcast_ref::().unwrap(); + self.sum += values.iter().flatten().sum::() * self.factor; + Ok(()) + } + + fn merge_batch(&mut self, states: &[ArrayRef]) -> Result<()> { + let states = states[0].as_any().downcast_ref::().unwrap(); + self.sum += states.iter().flatten().sum::(); + Ok(()) + } + + fn evaluate(&mut self) -> Result { + Ok(ScalarValue::Int64(Some(self.sum))) + } + + fn state(&mut self) -> Result> { + Ok(vec![ScalarValue::Int64(Some(self.sum))]) + } + + fn size(&self) -> usize { + size_of_val(self) + } +} + +/// An unrelated aggregate decoder, so the registry is not empty. +struct OtherAgg; +impl AggregateUdfFromProto for OtherAgg { + const NAME: &'static str = "datafusion.tests.OtherAgg"; + fn try_from_proto( + _payload: &[u8], + _name: &str, + _ctx: &TaskContext, + ) -> Result> { + internal_err!("unused") + } +} + +fn schema() -> Arc { + Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, true)])) +} + +fn source() -> Result> { + let schema = schema(); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int64Array::from(vec![1, 2, 3]))], + )?; + Ok(MemorySourceConfig::try_new_exec( + &[vec![batch]], + schema, + None, + )?) +} + +fn agg_expr(udaf: AggregateUDF) -> Result> { + let schema = schema(); + let alias = udaf.name().to_string(); + Ok(Arc::new( + AggregateExprBuilder::new(Arc::new(udaf), vec![col("x", &schema)?]) + .schema(schema) + .alias(alias) + .build()?, + )) +} + +fn aggregate(udafs: Vec) -> Result> { + let exprs = udafs + .into_iter() + .map(agg_expr) + .collect::>>()?; + let filters = vec![None; exprs.len()]; + Ok(Arc::new(AggregateExec::try_new( + AggregateMode::Single, + PhysicalGroupBy::new(vec![], vec![], vec![], false), + exprs, + filters, + source()?, + schema(), + )?)) +} + +fn window(udaf: AggregateUDF) -> Result> { + let expr = Arc::new(PlainAggregateWindowExpr::new( + agg_expr(udaf)?, + &[], + &[], + Arc::new(WindowFrame::new(None)), + None, + )); + Ok(Arc::new(WindowAggExec::try_new( + vec![expr], + source()?, + false, + )?)) +} + +fn registry_session() -> Result { + let mut config = SessionConfig::new(); + config.update_extension(SumScaled::register_proto)?; + config.update_extension(OtherAgg::register_proto)?; + Ok(SessionContext::new_with_config(config)) +} + +async fn run( + plan: Arc, + ctx: &SessionContext, +) -> Result>> { + let batches = collect(plan, ctx.task_ctx()).await?; + assert_eq!(batches.len(), 1); + Ok(batches[0] + .columns() + .iter() + .map(|c| { + let c = c.as_any().downcast_ref::().unwrap(); + c.values().to_vec() + }) + .collect()) +} + +/// The `PhysicalAggregateExprNode`s of an encoded `AggregateExec`. +fn aggregate_nodes( + plan: Arc, + codec: &dyn PhysicalExtensionCodec, +) -> Result> { + let node = PhysicalPlanNode::try_from_physical_plan(plan, codec)?; + let Some(PhysicalPlanType::Aggregate(agg)) = node.physical_plan_type else { + panic!("expected AggregateExecNode"); + }; + Ok(agg + .aggr_expr + .into_iter() + .map(|e| match e.expr_type { + Some(ExprType::AggregateExpr(node)) => node, + other => panic!("expected an aggregate expr, got {other:?}"), + }) + .collect()) +} + +#[tokio::test] +async fn one_type_two_sql_names_round_trip_in_aggregate_exec() -> Result<()> { + let plan = aggregate(vec![ + AggregateUDF::new_from_impl(SumScaled::new("sum_by_7", 7)), + AggregateUDF::new_from_impl(SumScaled::new("sum_by_3", 3)), + ])?; + let nodes = aggregate_nodes(Arc::clone(&plan), &DefaultPhysicalExtensionCodec {})?; + assert_eq!( + nodes + .iter() + .map(|n| (n.fun_type_name.as_deref(), n.fun_definition.clone())) + .collect::>(), + vec![ + (Some(SumScaled::NAME), Some(7i64.to_le_bytes().to_vec())), + (Some(SumScaled::NAME), Some(3i64.to_le_bytes().to_vec())), + ] + ); + + let bytes = physical_plan_to_bytes(plan)?; + let ctx = registry_session()?; + assert!(ctx.state().aggregate_functions().get("sum_by_7").is_none()); + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!(run(decoded, &ctx).await?, vec![vec![42], vec![18]]); + Ok(()) +} + +/// `PhysicalWindowExprNode` carries an aggregate function too. +#[tokio::test] +async fn stateful_udaf_round_trips_in_window_exec() -> Result<()> { + let plan = window(AggregateUDF::new_from_impl(SumScaled::new("sum_by_7", 7)))?; + let bytes = physical_plan_to_bytes(plan)?; + let ctx = registry_session()?; + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!( + run(decoded, &ctx).await?, + vec![vec![1, 2, 3], vec![42, 42, 42]] + ); + Ok(()) +} + +#[tokio::test] +async fn aliased_stateful_udaf_round_trips() -> Result<()> { + let udaf = + AggregateUDF::new_from_impl(SumScaled::new("sum_by_5", 5)).with_aliases(["sb5"]); + let bytes = physical_plan_to_bytes(aggregate(vec![udaf])?)?; + let ctx = registry_session()?; + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!(run(decoded, &ctx).await?, vec![vec![30]]); + Ok(()) +} + +#[test] +fn unregistered_type_name_errors() -> Result<()> { + let plan = aggregate(vec![AggregateUDF::new_from_impl(SumScaled::new( + "sum_by_7", 7, + ))])?; + let bytes = physical_plan_to_bytes(plan)?; + let mut config = SessionConfig::new(); + config.update_extension(OtherAgg::register_proto)?; + let ctx = SessionContext::new_with_config(config); + let err = physical_plan_from_bytes(&bytes, &ctx.task_ctx()).unwrap_err(); + assert!( + err.to_string().contains( + "No decoder is registered for the aggregate function type \ + 'datafusion.tests.SumScaled' (function 'sum_by_7'). Register it with \ + `AggregateUdfFromProto::register_proto`" + ), + "{err}" + ); + assert!( + err.to_string() + .contains("Registered aggregate function types: datafusion.tests.OtherAgg"), + "{err}" + ); + Ok(()) +} + +#[tokio::test] +async fn stateless_udaf_round_trips_by_name() -> Result<()> { + let sum = Arc::unwrap_or_clone(sum_udaf()); + let plan = aggregate(vec![sum])?; + let nodes = aggregate_nodes(Arc::clone(&plan), &DefaultPhysicalExtensionCodec {})?; + assert_eq!( + ( + nodes[0].fun_definition.clone(), + nodes[0].fun_type_name.clone() + ), + (None, None) + ); + + let bytes = physical_plan_to_bytes(plan)?; + let ctx = SessionContext::new(); + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!(run(decoded, &ctx).await?, vec![vec![6]]); + Ok(()) +} + +/// A codec that writes `fun_definition` itself. +#[derive(Debug)] +struct FactorCodec; +impl PhysicalExtensionCodec for FactorCodec { + fn try_decode( + &self, + _buf: &[u8], + _inputs: &[Arc], + _ctx: &TaskContext, + _proto_converter: &dyn datafusion_proto::physical_plan::PhysicalProtoConverterExtension, + ) -> Result> { + internal_err!("unused") + } + + fn try_encode( + &self, + _node: Arc, + _buf: &mut Vec, + _proto_converter: &dyn datafusion_proto::physical_plan::PhysicalProtoConverterExtension, + ) -> Result<()> { + internal_err!("unused") + } + + fn try_encode_udaf(&self, node: &AggregateUDF, buf: &mut Vec) -> Result<()> { + if node.name() == "codec_sum" { + buf.extend_from_slice(&11i64.to_le_bytes()); + } + Ok(()) + } + + fn try_decode_udaf(&self, name: &str, buf: &[u8]) -> Result> { + let factor = i64::from_le_bytes(buf.try_into().unwrap()); + Ok(Arc::new(AggregateUDF::new_from_impl(CodecSum( + SumScaled::new(name, factor), + )))) + } +} + +/// Like `SumScaled`, but with no `try_encode_state`: only the codec knows it. +#[derive(Debug, PartialEq, Eq, Hash)] +struct CodecSum(SumScaled); +impl AggregateUDFImpl for CodecSum { + fn name(&self) -> &str { + self.0.name() + } + fn signature(&self) -> &Signature { + self.0.signature() + } + fn return_type(&self, t: &[DataType]) -> Result { + self.0.return_type(t) + } + fn accumulator(&self, args: AccumulatorArgs) -> Result> { + self.0.accumulator(args) + } +} + +#[tokio::test] +async fn codec_written_definition_still_uses_codec() -> Result<()> { + let udaf = AggregateUDF::new_from_impl(CodecSum(SumScaled::new("codec_sum", 11))); + let plan = aggregate(vec![udaf])?; + let nodes = aggregate_nodes(Arc::clone(&plan), &FactorCodec)?; + assert_eq!( + ( + nodes[0].fun_definition.clone(), + nodes[0].fun_type_name.clone() + ), + (Some(11i64.to_le_bytes().to_vec()), None) + ); + + let bytes = physical_plan_to_bytes_with_extension_codec(plan, &FactorCodec)?; + let ctx = registry_session()?; + let decoded = physical_plan_from_bytes_with_extension_codec( + &bytes, + &ctx.task_ctx(), + &FactorCodec, + )?; + assert_eq!(run(decoded, &ctx).await?, vec![vec![66]]); + Ok(()) +} diff --git a/datafusion/proto/tests/cases/plans/udf_registry.rs b/datafusion/proto/tests/cases/plans/udf_registry.rs new file mode 100644 index 0000000000000..47b3d9d158a71 --- /dev/null +++ b/datafusion/proto/tests/cases/plans/udf_registry.rs @@ -0,0 +1,394 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Stateful scalar UDFs decoded through a `ProtoDecoderRegistry` instead of a +//! `PhysicalExtensionCodec`. + +use std::sync::Arc; + +use arrow::array::{Array, Int64Array}; +use arrow::datatypes::{DataType, Field, Schema}; +use arrow::record_batch::RecordBatch; +use datafusion::datasource::memory::MemorySourceConfig; +use datafusion::execution::TaskContext; +use datafusion::physical_plan::expressions::col; +use datafusion::physical_plan::projection::ProjectionExec; +use datafusion::physical_plan::{ExecutionPlan, collect}; +use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_common::{Result, exec_err, internal_err}; +use datafusion_execution::proto::ScalarUdfFromProto; +use datafusion_expr::async_udf::{AsyncScalarUDF, AsyncScalarUDFImpl}; +use datafusion_expr::{ + ColumnarValue, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, UDFState, + Volatility, create_udf, +}; +use datafusion_physical_expr::ScalarFunctionExpr; +use datafusion_physical_expr_common::physical_expr::PhysicalExpr; +use datafusion_proto::bytes::{ + physical_plan_from_bytes, physical_plan_from_bytes_with_extension_codec, + physical_plan_to_bytes, physical_plan_to_bytes_with_extension_codec, +}; +use datafusion_proto::physical_plan::to_proto::serialize_physical_expr; +use datafusion_proto::physical_plan::{ + DefaultPhysicalExtensionCodec, PhysicalExtensionCodec, +}; +use datafusion_proto::protobuf::physical_expr_node::ExprType; + +/// `scale_by(x)` multiplies `x` by `factor`. One type, many SQL names. +#[derive(Debug, PartialEq, Eq, Hash)] +struct ScaleBy { + name: String, + factor: i64, + signature: Signature, +} + +impl ScaleBy { + fn new(name: &str, factor: i64) -> Self { + Self { + name: name.to_string(), + factor, + signature: Signature::exact(vec![DataType::Int64], Volatility::Immutable), + } + } +} + +impl ScalarUDFImpl for ScaleBy { + fn name(&self) -> &str { + &self.name + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn return_type(&self, _arg_types: &[DataType]) -> Result { + Ok(DataType::Int64) + } + + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result { + let ColumnarValue::Array(array) = &args.args[0] else { + return exec_err!("expected an array"); + }; + let array = array.as_any().downcast_ref::().unwrap(); + let out: Int64Array = array.iter().map(|v| v.map(|v| v * self.factor)).collect(); + Ok(ColumnarValue::Array(Arc::new(out))) + } + + fn try_encode_state(&self) -> Result> { + Ok(Some(UDFState { + type_name: Self::NAME, + payload: self.factor.to_le_bytes().to_vec(), + })) + } +} + +impl ScalarUdfFromProto for ScaleBy { + const NAME: &'static str = "datafusion.tests.ScaleBy"; + + fn try_from_proto( + payload: &[u8], + name: &str, + _ctx: &TaskContext, + ) -> Result> { + let factor = i64::from_le_bytes(payload.try_into().unwrap()); + Ok(Arc::new(ScalarUDF::new_from_impl(ScaleBy::new( + name, factor, + )))) + } +} + +/// `ScaleBy` under the async wrapper. The decoder re-wraps. +#[async_trait::async_trait] +impl AsyncScalarUDFImpl for ScaleBy { + async fn invoke_async_with_args( + &self, + args: ScalarFunctionArgs, + ) -> Result { + self.invoke_with_args(args) + } +} + +#[derive(Debug, PartialEq, Eq, Hash)] +struct AsyncScaleBy; +impl ScalarUdfFromProto for AsyncScaleBy { + const NAME: &'static str = "datafusion.tests.AsyncScaleBy"; + fn try_from_proto( + payload: &[u8], + name: &str, + _ctx: &TaskContext, + ) -> Result> { + let factor = i64::from_le_bytes(payload.try_into().unwrap()); + Ok(Arc::new( + AsyncScalarUDF::new(Arc::new(ScaleBy::new(name, factor))).into_scalar_udf(), + )) + } +} + +fn schema() -> Arc { + Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, true)])) +} + +fn call(udf: ScalarUDF) -> Result> { + let schema = schema(); + Ok(Arc::new(ScalarFunctionExpr::try_new( + Arc::new(udf), + vec![col("x", &schema)?], + &schema, + Arc::new(Default::default()), + )?)) +} + +fn project(udfs: Vec) -> Result> { + let schema = schema(); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int64Array::from(vec![1, 2, 3]))], + )?; + let source = MemorySourceConfig::try_new_exec(&[vec![batch]], schema, None)?; + let exprs = udfs + .into_iter() + .map(|udf| { + let name = udf.name().to_string(); + Ok((call(udf)?, name)) + }) + .collect::>>()?; + Ok(Arc::new(ProjectionExec::try_new(exprs, source)?)) +} + +fn registry_session() -> Result { + let mut config = SessionConfig::new(); + config.update_extension(ScaleBy::register_proto)?; + config.update_extension(AsyncScaleBy::register_proto)?; + Ok(SessionContext::new_with_config(config)) +} + +async fn run( + plan: Arc, + ctx: &SessionContext, +) -> Result>> { + let batches = collect(plan, ctx.task_ctx()).await?; + let batch = &batches[0]; + Ok(batch + .columns() + .iter() + .map(|c| { + let c = c.as_any().downcast_ref::().unwrap(); + c.values().to_vec() + }) + .collect()) +} + +#[tokio::test] +async fn one_type_two_sql_names_round_trip() -> Result<()> { + let plan = project(vec![ + ScalarUDF::new_from_impl(ScaleBy::new("scale_by_7", 7)), + ScalarUDF::new_from_impl(ScaleBy::new("scale_by_3", 3)), + ])?; + let bytes = physical_plan_to_bytes(plan)?; + + let ctx = registry_session()?; + assert!(ctx.state().scalar_functions().get("scale_by_7").is_none()); + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!( + run(decoded, &ctx).await?, + vec![vec![7, 14, 21], vec![3, 6, 9]] + ); + Ok(()) +} + +#[test] +fn unregistered_type_name_errors() -> Result<()> { + let plan = project(vec![ScalarUDF::new_from_impl(ScaleBy::new( + "scale_by_7", + 7, + ))])?; + let bytes = physical_plan_to_bytes(plan)?; + let mut config = SessionConfig::new(); + config.update_extension(AsyncScaleBy::register_proto)?; + let ctx = SessionContext::new_with_config(config); + let err = physical_plan_from_bytes(&bytes, &ctx.task_ctx()).unwrap_err(); + assert!( + err.to_string().contains( + "No decoder is registered for the scalar function type \ + 'datafusion.tests.ScaleBy' (function 'scale_by_7')" + ), + "{err}" + ); + assert!( + err.to_string() + .contains("Registered scalar function types: datafusion.tests.AsyncScaleBy"), + "{err}" + ); + Ok(()) +} + +/// A decoder that ignores the SQL name it is given. +struct IgnoresName; +impl ScalarUdfFromProto for IgnoresName { + const NAME: &'static str = ScaleBy::NAME; + fn try_from_proto( + payload: &[u8], + _name: &str, + ctx: &TaskContext, + ) -> Result> { + ScaleBy::try_from_proto(payload, "other_name", ctx) + } +} + +#[test] +fn decoder_that_changes_the_sql_name_errors() -> Result<()> { + let plan = project(vec![ScalarUDF::new_from_impl(ScaleBy::new( + "scale_by_7", + 7, + ))])?; + let bytes = physical_plan_to_bytes(plan)?; + let mut config = SessionConfig::new(); + config.update_extension(IgnoresName::register_proto)?; + let ctx = SessionContext::new_with_config(config); + let err = physical_plan_from_bytes(&bytes, &ctx.task_ctx()).unwrap_err(); + assert!( + err.to_string().contains( + "Decoder for scalar function type 'datafusion.tests.ScaleBy' returned a \ + function named 'other_name', expected 'scale_by_7'" + ), + "{err}" + ); + Ok(()) +} + +#[tokio::test] +async fn stateless_udf_round_trips_by_name() -> Result<()> { + let udf = create_udf( + "plus_one", + vec![DataType::Int64], + DataType::Int64, + Volatility::Immutable, + Arc::new(|args: &[ColumnarValue]| { + let ColumnarValue::Array(a) = &args[0] else { + unreachable!() + }; + let a = a.as_any().downcast_ref::().unwrap(); + let out: Int64Array = a.iter().map(|v| v.map(|v| v + 1)).collect(); + Ok(ColumnarValue::Array(Arc::new(out))) + }), + ); + let node = + serialize_physical_expr(&call(udf.clone())?, &DefaultPhysicalExtensionCodec {})?; + let Some(ExprType::ScalarUdf(node)) = node.expr_type else { + panic!() + }; + assert_eq!((node.fun_definition, node.fun_type_name), (None, None)); + + let bytes = physical_plan_to_bytes(project(vec![udf.clone()])?)?; + let ctx = SessionContext::new(); + ctx.register_udf(udf); + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!(run(decoded, &ctx).await?, vec![vec![2, 3, 4]]); + Ok(()) +} + +#[tokio::test] +async fn aliased_stateful_udf_round_trips() -> Result<()> { + let udf = + ScalarUDF::new_from_impl(ScaleBy::new("scale_by_5", 5)).with_aliases(["sb5"]); + let bytes = physical_plan_to_bytes(project(vec![udf])?)?; + let ctx = registry_session()?; + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!(run(decoded, &ctx).await?, vec![vec![5, 10, 15]]); + Ok(()) +} + +/// The async wrapper must forward `try_encode_state`, or the payload is lost +/// and the decoder silently looks the function up by name. +#[test] +fn async_wrapped_stateful_udf_keeps_state() -> Result<()> { + let udf = + AsyncScalarUDF::new(Arc::new(ScaleBy::new("scale_by_4", 4))).into_scalar_udf(); + let node = serialize_physical_expr(&call(udf)?, &DefaultPhysicalExtensionCodec {})?; + let Some(ExprType::ScalarUdf(node)) = node.expr_type else { + panic!() + }; + // `ScaleBy` writes its own NAME, not the async one: the wrapper forwards + // the inner type's state, so the decoder must know to re-wrap. + assert_eq!(node.fun_type_name.as_deref(), Some(ScaleBy::NAME)); + assert_eq!(node.fun_definition, Some(4i64.to_le_bytes().to_vec())); + Ok(()) +} + +/// A codec that writes `fun_definition` itself, for a stateless UDF. +#[derive(Debug)] +struct NameCodec; +impl PhysicalExtensionCodec for NameCodec { + fn try_decode( + &self, + _buf: &[u8], + _inputs: &[Arc], + _ctx: &TaskContext, + _proto_converter: &dyn datafusion_proto::physical_plan::PhysicalProtoConverterExtension, + ) -> Result> { + internal_err!("unused") + } + + fn try_encode( + &self, + _node: Arc, + _buf: &mut Vec, + _proto_converter: &dyn datafusion_proto::physical_plan::PhysicalProtoConverterExtension, + ) -> Result<()> { + internal_err!("unused") + } + + fn try_encode_udf(&self, node: &ScalarUDF, buf: &mut Vec) -> Result<()> { + if node.name() == "codec_scale" { + buf.extend_from_slice(&11i64.to_le_bytes()); + } + Ok(()) + } + + fn try_decode_udf(&self, name: &str, buf: &[u8]) -> Result> { + let factor = i64::from_le_bytes(buf.try_into().unwrap()); + Ok(Arc::new(ScalarUDF::new_from_impl(CodecScale( + ScaleBy::new(name, factor), + )))) + } +} + +/// Like `ScaleBy`, but with no `try_encode_state`: only the codec knows it. +#[derive(Debug, PartialEq, Eq, Hash)] +struct CodecScale(ScaleBy); +impl ScalarUDFImpl for CodecScale { + fn name(&self) -> &str { + self.0.name() + } + fn signature(&self) -> &Signature { + self.0.signature() + } + fn return_type(&self, t: &[DataType]) -> Result { + self.0.return_type(t) + } + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result { + self.0.invoke_with_args(args) + } +} + +#[tokio::test] +async fn codec_written_definition_still_uses_codec() -> Result<()> { + let udf = ScalarUDF::new_from_impl(CodecScale(ScaleBy::new("codec_scale", 11))); + let node = serialize_physical_expr(&call(udf.clone())?, &NameCodec)?; + let Some(ExprType::ScalarUdf(node)) = node.expr_type else { + panic!() + }; + assert_eq!(node.fun_type_name, None); + + let bytes = + physical_plan_to_bytes_with_extension_codec(project(vec![udf])?, &NameCodec)?; + let ctx = registry_session()?; + let decoded = physical_plan_from_bytes_with_extension_codec( + &bytes, + &ctx.task_ctx(), + &NameCodec, + )?; + assert_eq!(run(decoded, &ctx).await?, vec![vec![11, 22, 33]]); + Ok(()) +} diff --git a/datafusion/proto/tests/cases/plans/udwf_registry.rs b/datafusion/proto/tests/cases/plans/udwf_registry.rs new file mode 100644 index 0000000000000..3c46315633740 --- /dev/null +++ b/datafusion/proto/tests/cases/plans/udwf_registry.rs @@ -0,0 +1,378 @@ +// SPDX-License-Identifier: Apache-2.0 +// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership +// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements + +//! Stateful window UDFs decoded through a `ProtoDecoderRegistry` instead of a +//! `PhysicalExtensionCodec`. + +use std::sync::Arc; + +use arrow::array::{Array, ArrayRef, Int64Array}; +use arrow::datatypes::{DataType, Field, FieldRef, Schema}; +use arrow::record_batch::RecordBatch; +use datafusion::datasource::memory::MemorySourceConfig; +use datafusion::execution::TaskContext; +use datafusion::functions_window::row_number::row_number_udwf; +use datafusion::physical_expr::window::StandardWindowExpr; +use datafusion::physical_plan::windows::{WindowAggExec, create_udwf_window_expr}; +use datafusion::physical_plan::{ExecutionPlan, collect}; +use datafusion::prelude::{SessionConfig, SessionContext}; +use datafusion_common::{Result, internal_err}; +use datafusion_execution::proto::WindowUdfFromProto; +use datafusion_expr::function::{PartitionEvaluatorArgs, WindowUDFFieldArgs}; +use datafusion_expr::{ + PartitionEvaluator, Signature, UDFState, Volatility, WindowFrame, WindowUDF, + WindowUDFImpl, +}; +use datafusion_proto::bytes::{ + physical_plan_from_bytes, physical_plan_from_bytes_with_extension_codec, + physical_plan_to_bytes, physical_plan_to_bytes_with_extension_codec, +}; +use datafusion_proto::physical_plan::{ + AsExecutionPlan, DefaultPhysicalExtensionCodec, PhysicalExtensionCodec, +}; +use datafusion_proto::protobuf::physical_plan_node::PhysicalPlanType; +use datafusion_proto::protobuf::{PhysicalPlanNode, PhysicalWindowExprNode}; + +/// `row_times()` returns the row number times `factor`. One type, many SQL +/// names. +#[derive(Debug, PartialEq, Eq, Hash)] +struct RowTimes { + name: String, + factor: i64, + signature: Signature, +} + +impl RowTimes { + fn new(name: &str, factor: i64) -> Self { + Self { + name: name.to_string(), + factor, + signature: Signature::exact(vec![], Volatility::Immutable), + } + } +} + +impl WindowUDFImpl for RowTimes { + fn name(&self) -> &str { + &self.name + } + + fn signature(&self) -> &Signature { + &self.signature + } + + fn partition_evaluator( + &self, + _args: PartitionEvaluatorArgs, + ) -> Result> { + Ok(Box::new(RowTimesEvaluator { + factor: self.factor, + })) + } + + fn field(&self, field_args: WindowUDFFieldArgs) -> Result { + Ok(Arc::new(Field::new( + field_args.name(), + DataType::Int64, + false, + ))) + } + + fn try_encode_state(&self) -> Result> { + Ok(Some(UDFState { + type_name: Self::NAME, + payload: self.factor.to_le_bytes().to_vec(), + })) + } +} + +impl WindowUdfFromProto for RowTimes { + const NAME: &'static str = "datafusion.tests.RowTimes"; + + fn try_from_proto( + payload: &[u8], + name: &str, + _ctx: &TaskContext, + ) -> Result> { + let factor = i64::from_le_bytes(payload.try_into().unwrap()); + Ok(Arc::new(WindowUDF::new_from_impl(RowTimes::new( + name, factor, + )))) + } +} + +#[derive(Debug)] +struct RowTimesEvaluator { + factor: i64, +} + +impl PartitionEvaluator for RowTimesEvaluator { + fn evaluate_all( + &mut self, + _values: &[ArrayRef], + num_rows: usize, + ) -> Result { + Ok(Arc::new(Int64Array::from_iter_values( + (1..=num_rows as i64).map(|n| n * self.factor), + ))) + } +} + +/// An unrelated window decoder, so the registry is not empty. +struct OtherWindow; +impl WindowUdfFromProto for OtherWindow { + const NAME: &'static str = "datafusion.tests.OtherWindow"; + fn try_from_proto( + _payload: &[u8], + _name: &str, + _ctx: &TaskContext, + ) -> Result> { + internal_err!("unused") + } +} + +fn schema() -> Arc { + Arc::new(Schema::new(vec![Field::new("x", DataType::Int64, true)])) +} + +fn window(udwfs: Vec) -> Result> { + let schema = schema(); + let batch = RecordBatch::try_new( + Arc::clone(&schema), + vec![Arc::new(Int64Array::from(vec![10, 20, 30]))], + )?; + let source = MemorySourceConfig::try_new_exec(&[vec![batch]], schema.clone(), None)?; + let exprs = udwfs + .into_iter() + .map(|udwf| { + let name = udwf.name().to_string(); + let expr = + create_udwf_window_expr(&Arc::new(udwf), &[], &schema, name, false)?; + Ok(Arc::new(StandardWindowExpr::new( + expr, + &[], + &[], + Arc::new(WindowFrame::new(None)), + )) as _) + }) + .collect::>>()?; + Ok(Arc::new(WindowAggExec::try_new(exprs, source, false)?)) +} + +fn registry_session() -> Result { + let mut config = SessionConfig::new(); + config.update_extension(RowTimes::register_proto)?; + config.update_extension(OtherWindow::register_proto)?; + Ok(SessionContext::new_with_config(config)) +} + +async fn run( + plan: Arc, + ctx: &SessionContext, +) -> Result>> { + let batches = collect(plan, ctx.task_ctx()).await?; + assert_eq!(batches.len(), 1); + Ok(batches[0] + .columns() + .iter() + .map(|c| { + let c = c.as_any().downcast_ref::().unwrap(); + c.values().to_vec() + }) + .collect()) +} + +/// The `PhysicalWindowExprNode`s of an encoded `WindowAggExec`. +fn window_nodes( + plan: Arc, + codec: &dyn PhysicalExtensionCodec, +) -> Result> { + let node = PhysicalPlanNode::try_from_physical_plan(plan, codec)?; + let Some(PhysicalPlanType::Window(window)) = node.physical_plan_type else { + panic!("expected WindowAggExecNode"); + }; + Ok(window.window_expr) +} + +#[tokio::test] +async fn one_type_two_sql_names_round_trip_in_window_exec() -> Result<()> { + let plan = window(vec![ + WindowUDF::new_from_impl(RowTimes::new("row_times_7", 7)), + WindowUDF::new_from_impl(RowTimes::new("row_times_3", 3)), + ])?; + let nodes = window_nodes(Arc::clone(&plan), &DefaultPhysicalExtensionCodec {})?; + assert_eq!( + nodes + .iter() + .map(|n| (n.fun_type_name.as_deref(), n.fun_definition.clone())) + .collect::>(), + vec![ + (Some(RowTimes::NAME), Some(7i64.to_le_bytes().to_vec())), + (Some(RowTimes::NAME), Some(3i64.to_le_bytes().to_vec())), + ] + ); + + let bytes = physical_plan_to_bytes(plan)?; + let ctx = registry_session()?; + assert!(ctx.state().window_functions().get("row_times_7").is_none()); + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!( + run(decoded, &ctx).await?, + vec![vec![10, 20, 30], vec![7, 14, 21], vec![3, 6, 9]] + ); + Ok(()) +} + +#[tokio::test] +async fn aliased_stateful_udwf_round_trips() -> Result<()> { + let udwf = + WindowUDF::new_from_impl(RowTimes::new("row_times_5", 5)).with_aliases(["rt5"]); + let bytes = physical_plan_to_bytes(window(vec![udwf])?)?; + let ctx = registry_session()?; + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + assert_eq!( + run(decoded, &ctx).await?, + vec![vec![10, 20, 30], vec![5, 10, 15]] + ); + Ok(()) +} + +#[test] +fn unregistered_type_name_errors() -> Result<()> { + let plan = window(vec![WindowUDF::new_from_impl(RowTimes::new( + "row_times_7", + 7, + ))])?; + let bytes = physical_plan_to_bytes(plan)?; + let mut config = SessionConfig::new(); + config.update_extension(OtherWindow::register_proto)?; + let ctx = SessionContext::new_with_config(config); + let err = physical_plan_from_bytes(&bytes, &ctx.task_ctx()).unwrap_err(); + assert!( + err.to_string().contains( + "No decoder is registered for the window function type \ + 'datafusion.tests.RowTimes' (function 'row_times_7'). Register it with \ + `WindowUdfFromProto::register_proto`" + ), + "{err}" + ); + assert!( + err.to_string() + .contains("Registered window function types: datafusion.tests.OtherWindow"), + "{err}" + ); + Ok(()) +} + +#[tokio::test] +async fn stateless_udwf_round_trips_by_name() -> Result<()> { + let row_number = Arc::unwrap_or_clone(row_number_udwf()); + let plan = window(vec![row_number])?; + let nodes = window_nodes(Arc::clone(&plan), &DefaultPhysicalExtensionCodec {})?; + assert_eq!( + ( + nodes[0].fun_definition.clone(), + nodes[0].fun_type_name.clone() + ), + (None, None) + ); + + let bytes = physical_plan_to_bytes(plan)?; + let ctx = SessionContext::new(); + let decoded = physical_plan_from_bytes(&bytes, &ctx.task_ctx())?; + let batches = collect(decoded, ctx.task_ctx()).await?; + let row_number = batches[0] + .column(1) + .as_any() + .downcast_ref::() + .unwrap(); + assert_eq!(row_number.values().to_vec(), vec![1, 2, 3]); + Ok(()) +} + +/// A codec that writes `fun_definition` itself. +#[derive(Debug)] +struct FactorCodec; +impl PhysicalExtensionCodec for FactorCodec { + fn try_decode( + &self, + _buf: &[u8], + _inputs: &[Arc], + _ctx: &TaskContext, + _proto_converter: &dyn datafusion_proto::physical_plan::PhysicalProtoConverterExtension, + ) -> Result> { + internal_err!("unused") + } + + fn try_encode( + &self, + _node: Arc, + _buf: &mut Vec, + _proto_converter: &dyn datafusion_proto::physical_plan::PhysicalProtoConverterExtension, + ) -> Result<()> { + internal_err!("unused") + } + + fn try_encode_udwf(&self, node: &WindowUDF, buf: &mut Vec) -> Result<()> { + if node.name() == "codec_rows" { + buf.extend_from_slice(&11i64.to_le_bytes()); + } + Ok(()) + } + + fn try_decode_udwf(&self, name: &str, buf: &[u8]) -> Result> { + let factor = i64::from_le_bytes(buf.try_into().unwrap()); + Ok(Arc::new(WindowUDF::new_from_impl(CodecRows( + RowTimes::new(name, factor), + )))) + } +} + +/// Like `RowTimes`, but with no `try_encode_state`: only the codec knows it. +#[derive(Debug, PartialEq, Eq, Hash)] +struct CodecRows(RowTimes); +impl WindowUDFImpl for CodecRows { + fn name(&self) -> &str { + self.0.name() + } + fn signature(&self) -> &Signature { + self.0.signature() + } + fn partition_evaluator( + &self, + args: PartitionEvaluatorArgs, + ) -> Result> { + self.0.partition_evaluator(args) + } + fn field(&self, field_args: WindowUDFFieldArgs) -> Result { + self.0.field(field_args) + } +} + +#[tokio::test] +async fn codec_written_definition_still_uses_codec() -> Result<()> { + let udwf = WindowUDF::new_from_impl(CodecRows(RowTimes::new("codec_rows", 11))); + let plan = window(vec![udwf])?; + let nodes = window_nodes(Arc::clone(&plan), &FactorCodec)?; + assert_eq!( + ( + nodes[0].fun_definition.clone(), + nodes[0].fun_type_name.clone() + ), + (Some(11i64.to_le_bytes().to_vec()), None) + ); + + let bytes = physical_plan_to_bytes_with_extension_codec(plan, &FactorCodec)?; + let ctx = registry_session()?; + let decoded = physical_plan_from_bytes_with_extension_codec( + &bytes, + &ctx.task_ctx(), + &FactorCodec, + )?; + assert_eq!( + run(decoded, &ctx).await?, + vec![vec![10, 20, 30], vec![11, 22, 33]] + ); + Ok(()) +}