Apache DataFusion SQL Query Engine
feat(proto): udf decoding fallback (#15997)
Leonardo Yvens7af93e2e32ca
diff --git a/datafusion/proto/src/logical_plan/from_proto.rs b/datafusion/proto/src/logical_plan/from_proto.rsindex cac2f9db16..9f0489d6b0 100644--- a/datafusion/proto/src/logical_plan/from_proto.rs+++ b/datafusion/proto/src/logical_plan/from_proto.rs@@ -296,7 +296,9 @@ pub fn parse_expr(window_expr_node::WindowFunction::Udaf(udaf_name) => {let udaf_function = match &expr.fun_definition {Some(buf) => codec.try_decode_udaf(udaf_name, buf)?,- None => registry.udaf(udaf_name)?,+ None => registry+ .udaf(udaf_name)+ .or_else(|_| codec.try_decode_udaf(udaf_name, &[]))?,};let args = parse_exprs(&expr.exprs, registry, codec)?;@@ -313,7 +315,9 @@ pub fn parse_expr(window_expr_node::WindowFunction::Udwf(udwf_name) => {let udwf_function = match &expr.fun_definition {Some(buf) => codec.try_decode_udwf(udwf_name, buf)?,- None => registry.udwf(udwf_name)?,+ None => registry+ .udwf(udwf_name)+ .or_else(|_| codec.try_decode_udwf(udwf_name, &[]))?,};let args = parse_exprs(&expr.exprs, registry, codec)?;@@ -540,7 +544,9 @@ pub fn parse_expr(}) => {let scalar_fn = match fun_definition {Some(buf) => codec.try_decode_udf(fun_name, buf)?,- None => registry.udf(fun_name.as_str())?,+ None => registry+ .udf(fun_name.as_str())+ .or_else(|_| codec.try_decode_udf(fun_name, &[]))?,};Ok(Expr::ScalarFunction(expr::ScalarFunction::new_udf(scalar_fn,@@ -550,7 +556,9 @@ pub fn parse_expr(ExprType::AggregateUdfExpr(pb) => {let agg_fn = match &pb.fun_definition {Some(buf) => codec.try_decode_udaf(&pb.fun_name, buf)?,- None => registry.udaf(&pb.fun_name)?,+ None => registry+ .udaf(&pb.fun_name)+ .or_else(|_| codec.try_decode_udaf(&pb.fun_name, &[]))?,};Ok(Expr::AggregateFunction(expr::AggregateFunction::new_udf(diff --git a/datafusion/proto/src/physical_plan/from_proto.rs b/datafusion/proto/src/physical_plan/from_proto.rsindex c412dfed5d..ef79f4b43e 100644--- a/datafusion/proto/src/physical_plan/from_proto.rs+++ b/datafusion/proto/src/physical_plan/from_proto.rs@@ -152,13 +152,13 @@ pub fn parse_physical_window_expr(protobuf::physical_window_expr_node::WindowFunction::UserDefinedAggrFunction(udaf_name) => {WindowFunctionDefinition::AggregateUDF(match &proto.fun_definition {Some(buf) => codec.try_decode_udaf(udaf_name, buf)?,- None => registry.udaf(udaf_name)?+ None => registry.udaf(udaf_name).or_else(|_| codec.try_decode_udaf(udaf_name, &[]))?,})}protobuf::physical_window_expr_node::WindowFunction::UserDefinedWindowFunction(udwf_name) => {WindowFunctionDefinition::WindowUDF(match &proto.fun_definition {Some(buf) => codec.try_decode_udwf(udwf_name, buf)?,- None => registry.udwf(udwf_name)?+ None => registry.udwf(udwf_name).or_else(|_| codec.try_decode_udwf(udwf_name, &[]))?})}}@@ -355,7 +355,9 @@ pub fn parse_physical_expr(ExprType::ScalarUdf(e) => {let udf = match &e.fun_definition {Some(buf) => codec.try_decode_udf(&e.name, buf)?,- None => registry.udf(e.name.as_str())?,+ None => registry+ .udf(e.name.as_str())+ .or_else(|_| codec.try_decode_udf(&e.name, &[]))?,};let scalar_fun_def = Arc::clone(&udf);diff --git a/datafusion/proto/src/physical_plan/mod.rs b/datafusion/proto/src/physical_plan/mod.rsindex 9b636d1510..7a85a2a8ef 100644--- a/datafusion/proto/src/physical_plan/mod.rs+++ b/datafusion/proto/src/physical_plan/mod.rs@@ -1050,7 +1050,12 @@ impl protobuf::PhysicalPlanNode {let agg_udf = match &agg_node.fun_definition {Some(buf) => extension_codec.try_decode_udaf(udaf_name, buf)?,- None => registry.udaf(udaf_name)?,+ None => {+ registry.udaf(udaf_name).or_else(|_| {+ extension_codec+ .try_decode_udaf(udaf_name, &[])+ })?+ }};AggregateExprBuilder::new(agg_udf, input_phy_expr)diff --git a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs b/datafusion/proto/tests/cases/roundtrip_logical_plan.rsindex 7ecb2c23a5..eee1bc23c9 100644--- a/datafusion/proto/tests/cases/roundtrip_logical_plan.rs+++ b/datafusion/proto/tests/cases/roundtrip_logical_plan.rs@@ -113,15 +113,21 @@ fn roundtrip_json_test(proto: &protobuf::LogicalExprNode) {#[cfg(not(feature = "json"))]fn roundtrip_json_test(_proto: &protobuf::LogicalExprNode) {}-// Given a DataFusion logical Expr, convert it to protobuf and back, using debug formatting to test-// equality.fn roundtrip_expr_test(initial_struct: Expr, ctx: SessionContext) {let extension_codec = DefaultLogicalExtensionCodec {};- let proto: protobuf::LogicalExprNode =- serialize_expr(&initial_struct, &extension_codec)- .unwrap_or_else(|e| panic!("Error serializing expression: {:?}", e));- let round_trip: Expr =- from_proto::parse_expr(&proto, &ctx, &extension_codec).unwrap();+ roundtrip_expr_test_with_codec(initial_struct, ctx, &extension_codec);+}++// Given a DataFusion logical Expr, convert it to protobuf and back, using debug formatting to test+// equality.+fn roundtrip_expr_test_with_codec(+ initial_struct: Expr,+ ctx: SessionContext,+ codec: &dyn LogicalExtensionCodec,+) {+ let proto: protobuf::LogicalExprNode = serialize_expr(&initial_struct, codec)+ .unwrap_or_else(|e| panic!("Error serializing expression: {:?}", e));+ let round_trip: Expr = from_proto::parse_expr(&proto, &ctx, codec).unwrap();assert_eq!(format!("{:?}", &initial_struct), format!("{round_trip:?}"));@@ -2185,8 +2191,7 @@ fn roundtrip_aggregate_udf() {roundtrip_expr_test(test_expr, ctx);}-#[test]-fn roundtrip_scalar_udf() {+fn dummy_udf() -> ScalarUDF {let scalar_fn = Arc::new(|args: &[ColumnarValue]| {let ColumnarValue::Array(array) = &args[0] else {panic!("should be array")@@ -2194,13 +2199,18 @@ fn roundtrip_scalar_udf() {Ok(ColumnarValue::from(Arc::new(array.clone()) as ArrayRef))});- let udf = create_udf(+ create_udf("dummy",vec![DataType::Utf8],DataType::Utf8,Volatility::Immutable,scalar_fn,- );+ )+}++#[test]+fn roundtrip_scalar_udf() {+ let udf = dummy_udf();let test_expr = Expr::ScalarFunction(ScalarFunction::new_udf(Arc::new(udf.clone()),@@ -2210,7 +2220,57 @@ fn roundtrip_scalar_udf() {let ctx = SessionContext::new();ctx.register_udf(udf);- roundtrip_expr_test(test_expr, ctx);+ roundtrip_expr_test(test_expr.clone(), ctx);++ // Now test loading the UDF without registering it in the context, but rather creating it in the+ // extension codec.+ #[derive(Debug)]+ struct DummyUDFExtensionCodec;++ impl LogicalExtensionCodec for DummyUDFExtensionCodec {+ fn try_decode(+ &self,+ _buf: &[u8],+ _inputs: &[LogicalPlan],+ _ctx: &SessionContext,+ ) -> Result<Extension> {+ not_impl_err!("LogicalExtensionCodec is not provided")+ }++ fn try_encode(&self, _node: &Extension, _buf: &mut Vec<u8>) -> Result<()> {+ not_impl_err!("LogicalExtensionCodec is not provided")+ }++ fn try_decode_table_provider(+ &self,+ _buf: &[u8],+ _table_ref: &TableReference,+ _schema: SchemaRef,+ _ctx: &SessionContext,+ ) -> Result<Arc<dyn TableProvider>> {+ not_impl_err!("LogicalExtensionCodec is not provided")+ }++ fn try_encode_table_provider(+ &self,+ _table_ref: &TableReference,+ _node: Arc<dyn TableProvider>,+ _buf: &mut Vec<u8>,+ ) -> Result<()> {+ not_impl_err!("LogicalExtensionCodec is not provided")+ }++ fn try_decode_udf(&self, name: &str, _buf: &[u8]) -> Result<Arc<ScalarUDF>> {+ if name == "dummy" {+ Ok(Arc::new(dummy_udf()))+ } else {+ Err(DataFusionError::Internal(format!("UDF {name} not found")))+ }+ }+ }++ let ctx = SessionContext::new();+ roundtrip_expr_test_with_codec(test_expr, ctx, &DummyUDFExtensionCodec)}#[test]diff --git a/datafusion/proto/tests/cases/serialize.rs b/datafusion/proto/tests/cases/serialize.rsindex d15e62909f..ed99150831 100644--- a/datafusion/proto/tests/cases/serialize.rs+++ b/datafusion/proto/tests/cases/serialize.rs@@ -83,7 +83,7 @@ fn udf_roundtrip_with_registry() {#[test]#[should_panic(- expected = "No function registry provided to deserialize, so can not deserialize User Defined Function 'dummy'"+ expected = "LogicalExtensionCodec is not provided for scalar function dummy")]fn udf_roundtrip_without_registry() {let ctx = context_with_udf();