Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 4 additions & 0 deletions datafusion/execution/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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"] }
Expand Down
2 changes: 2 additions & 0 deletions datafusion/execution/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
251 changes: 251 additions & 0 deletions datafusion/execution/src/proto.rs
Original file line number Diff line number Diff line change
@@ -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<Arc<ScalarUDF>>;

/// Register this decoder in `registry`, under [`Self::NAME`].
fn register_proto(registry: &mut ProtoDecoderRegistry) -> Result<()> {
registry.register_decoder::<ScalarUDF, Self, ScalarUdfDecoder>(
Self::NAME,
Self::try_from_proto,
)
}
}

type ScalarUdfDecoder = fn(&[u8], &str, &TaskContext) -> Result<Arc<ScalarUDF>>;

/// 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<Result<Arc<ScalarUDF>>> {
let decoder = registry.decoder::<ScalarUDF, ScalarUdfDecoder>(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<Item = &str> {
registry.names::<ScalarUDF>()
}

/// 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<Arc<AggregateUDF>>;

/// Register this decoder in `registry`, under [`Self::NAME`].
fn register_proto(registry: &mut ProtoDecoderRegistry) -> Result<()> {
registry.register_decoder::<AggregateUDF, Self, AggregateUdfDecoder>(
Self::NAME,
Self::try_from_proto,
)
}
}

type AggregateUdfDecoder = fn(&[u8], &str, &TaskContext) -> Result<Arc<AggregateUDF>>;

/// 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<Result<Arc<AggregateUDF>>> {
let decoder = registry.decoder::<AggregateUDF, AggregateUdfDecoder>(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<Item = &str> {
registry.names::<AggregateUDF>()
}

/// 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<Arc<WindowUDF>>;

/// Register this decoder in `registry`, under [`Self::NAME`].
fn register_proto(registry: &mut ProtoDecoderRegistry) -> Result<()> {
registry.register_decoder::<WindowUDF, Self, WindowUdfDecoder>(
Self::NAME,
Self::try_from_proto,
)
}
}

type WindowUdfDecoder = fn(&[u8], &str, &TaskContext) -> Result<Arc<WindowUDF>>;

/// 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<Result<Arc<WindowUDF>>> {
let decoder = registry.decoder::<WindowUDF, WindowUdfDecoder>(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<Item = &str> {
registry.names::<WindowUDF>()
}

/// 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<Arc<HigherOrderUDF>>;

/// Register this decoder in `registry`, under [`Self::NAME`].
fn register_proto(registry: &mut ProtoDecoderRegistry) -> Result<()> {
registry.register_decoder::<HigherOrderUDF, Self, HigherOrderUdfDecoder>(
Self::NAME,
Self::try_from_proto,
)
}
}

type HigherOrderUdfDecoder = fn(&[u8], &str, &TaskContext) -> Result<Arc<HigherOrderUDF>>;

/// 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<Result<Arc<HigherOrderUDF>>> {
let decoder = registry.decoder::<HigherOrderUDF, HigherOrderUdfDecoder>(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<Item = &str> {
registry.names::<HigherOrderUDF>()
}
4 changes: 4 additions & 0 deletions datafusion/expr/src/async_udf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,10 @@ impl ScalarUDFImpl for AsyncScalarUDF {
self.inner.name()
}

fn try_encode_state(&self) -> Result<Option<crate::UDFState>> {
self.inner.try_encode_state()
}

fn signature(&self) -> &Signature {
self.inner.signature()
}
Expand Down
23 changes: 22 additions & 1 deletion datafusion/expr/src/higher_order_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<Option<UDFState>> {
Ok(None)
}

/// Returns any aliases (alternate names) for this function.
///
/// Aliases can be used to invoke the same function using different names.
Expand Down Expand Up @@ -965,6 +977,11 @@ impl HigherOrderUDF {
self.inner.name()
}

/// See [`HigherOrderUDFImpl::try_encode_state`].
pub fn try_encode_state(&self) -> Result<Option<UDFState>> {
self.inner.try_encode_state()
}

/// Returns the aliases for this function.
///
/// See [`HigherOrderUDF::with_aliases`] for more details.
Expand Down Expand Up @@ -1099,6 +1116,10 @@ impl HigherOrderUDFImpl for AliasedHigherOrderUDFImpl {
self.inner.name()
}

fn try_encode_state(&self) -> Result<Option<UDFState>> {
self.inner.try_encode_state()
}

fn aliases(&self) -> &[String] {
&self.aliases
}
Expand Down
1 change: 1 addition & 0 deletions datafusion/expr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down
Loading