Skip to main content

datafusion_physical_expr/
async_scalar_function.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use crate::ScalarFunctionExpr;
6use arrow::array::RecordBatch;
7use arrow::compute::concat;
8use arrow::datatypes::{DataType, Field, FieldRef, Schema};
9use datafusion_common::Result;
10use datafusion_common::config::ConfigOptions;
11use datafusion_common::{internal_err, not_impl_err};
12use datafusion_expr::ScalarFunctionArgs;
13use datafusion_expr::async_udf::AsyncScalarUDF;
14use datafusion_expr_common::columnar_value::ColumnarValue;
15use datafusion_physical_expr_common::physical_expr::PhysicalExpr;
16use std::fmt::Display;
17use std::hash::{Hash, Hasher};
18use std::sync::Arc;
19
20/// Wrapper around a scalar function that can be evaluated asynchronously
21#[derive(Debug, Clone, Eq)]
22pub struct AsyncFuncExpr {
23    /// The name of the output column this function will generate
24    pub name: String,
25    /// The actual function (always `ScalarFunctionExpr`)
26    pub func: Arc<dyn PhysicalExpr>,
27    /// The field that this function will return
28    return_field: FieldRef,
29}
30
31impl Display for AsyncFuncExpr {
32    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
33        write!(f, "async_expr(name={}, expr={})", self.name, self.func)
34    }
35}
36
37impl PartialEq for AsyncFuncExpr {
38    fn eq(&self, other: &Self) -> bool {
39        self.name == other.name && self.func == Arc::clone(&other.func)
40    }
41}
42
43impl Hash for AsyncFuncExpr {
44    fn hash<H: Hasher>(&self, state: &mut H) {
45        self.name.hash(state);
46        self.func.as_ref().hash(state);
47    }
48}
49
50impl AsyncFuncExpr {
51    /// create a new AsyncFuncExpr
52    pub fn try_new(
53        name: impl Into<String>,
54        func: Arc<dyn PhysicalExpr>,
55        schema: &Schema,
56    ) -> Result<Self> {
57        let Some(_) = func.downcast_ref::<ScalarFunctionExpr>() else {
58            return internal_err!(
59                "unexpected function type, expected ScalarFunctionExpr, got: {:?}",
60                func
61            );
62        };
63
64        let return_field = func.return_field(schema)?;
65        Ok(Self {
66            name: name.into(),
67            func,
68            return_field,
69        })
70    }
71
72    /// return the name of the output column
73    pub fn name(&self) -> &str {
74        &self.name
75    }
76
77    /// Return the output field generated by evaluating this function
78    #[deprecated(since = "55.0.0", note = "Use return_field instead")]
79    pub fn field(&self, _input_schema: &Schema) -> Result<Field> {
80        Ok(self.return_field.as_ref().clone().with_name(&self.name))
81    }
82
83    /// Return the ideal batch size for this function
84    pub fn ideal_batch_size(&self) -> Result<Option<usize>> {
85        if let Some(expr) = self.func.downcast_ref::<ScalarFunctionExpr>()
86            && let Some(udf) = expr.fun().inner().downcast_ref::<AsyncScalarUDF>()
87        {
88            return Ok(udf.ideal_batch_size());
89        }
90        not_impl_err!("Can't get ideal_batch_size from {:?}", self.func)
91    }
92
93    /// This (async) function is called for each record batch to evaluate the LLM expressions
94    ///
95    /// The output is the output of evaluating the async expression and the input record batch
96    pub async fn invoke_with_args(
97        &self,
98        batch: &RecordBatch,
99        config_options: Arc<ConfigOptions>,
100    ) -> Result<ColumnarValue> {
101        let Some(scalar_function_expr) = self.func.downcast_ref::<ScalarFunctionExpr>()
102        else {
103            return internal_err!(
104                "unexpected function type, expected ScalarFunctionExpr, got: {:?}",
105                self.func
106            );
107        };
108
109        let Some(async_udf) = scalar_function_expr
110            .fun()
111            .inner()
112            .downcast_ref::<AsyncScalarUDF>()
113        else {
114            return not_impl_err!(
115                "Don't know how to evaluate async function: {:?}",
116                scalar_function_expr
117            );
118        };
119
120        let arg_fields = scalar_function_expr
121            .args()
122            .iter()
123            .map(|e| e.return_field(batch.schema_ref()))
124            .collect::<Result<Vec<_>>>()?;
125
126        let mut result_batches = vec![];
127        if let Some(ideal_batch_size) = self.ideal_batch_size()? {
128            let mut remainder = batch.clone();
129            while remainder.num_rows() > 0 {
130                let size = if ideal_batch_size > remainder.num_rows() {
131                    remainder.num_rows()
132                } else {
133                    ideal_batch_size
134                };
135
136                let current_batch = remainder.slice(0, size); // get next 10 rows
137                remainder = remainder.slice(size, remainder.num_rows() - size);
138                let args = scalar_function_expr
139                    .args()
140                    .iter()
141                    .map(|e| e.evaluate(&current_batch))
142                    .collect::<Result<Vec<_>>>()?;
143                result_batches.push(
144                    async_udf
145                        .invoke_async_with_args(ScalarFunctionArgs {
146                            args,
147                            arg_fields: arg_fields.clone(),
148                            number_rows: current_batch.num_rows(),
149                            return_field: Arc::clone(&self.return_field),
150                            config_options: Arc::clone(&config_options),
151                        })
152                        .await?
153                        .into_array_of_size(current_batch.num_rows())?,
154                );
155            }
156        } else {
157            let args = scalar_function_expr
158                .args()
159                .iter()
160                .map(|e| e.evaluate(batch))
161                .collect::<Result<Vec<_>>>()?;
162
163            result_batches.push(
164                async_udf
165                    .invoke_async_with_args(ScalarFunctionArgs {
166                        args: args.to_vec(),
167                        arg_fields,
168                        number_rows: batch.num_rows(),
169                        return_field: Arc::clone(&self.return_field),
170                        config_options: Arc::clone(&config_options),
171                    })
172                    .await?
173                    .into_array_of_size(batch.num_rows())?,
174            );
175        }
176
177        // Get references to the arrays as dyn Array to call concat
178        let dyn_arrays = result_batches
179            .iter()
180            .map(|arr| arr as &dyn arrow::array::Array)
181            .collect::<Vec<_>>();
182        let result_array = concat(&dyn_arrays)?;
183        Ok(ColumnarValue::Array(result_array))
184    }
185}
186
187impl PhysicalExpr for AsyncFuncExpr {
188    fn data_type(&self, input_schema: &Schema) -> Result<DataType> {
189        self.func.data_type(input_schema)
190    }
191
192    fn return_field(&self, _input_schema: &Schema) -> Result<FieldRef> {
193        Ok(Arc::new(
194            self.return_field.as_ref().clone().with_name(&self.name),
195        ))
196    }
197
198    fn nullable(&self, input_schema: &Schema) -> Result<bool> {
199        self.func.nullable(input_schema)
200    }
201
202    fn evaluate(&self, _batch: &RecordBatch) -> Result<ColumnarValue> {
203        // TODO: implement this for scalar value input
204        not_impl_err!("AsyncFuncExpr.evaluate")
205    }
206
207    fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> {
208        self.func.children()
209    }
210
211    fn with_new_children(
212        self: Arc<Self>,
213        children: Vec<Arc<dyn PhysicalExpr>>,
214    ) -> Result<Arc<dyn PhysicalExpr>> {
215        let new_func = Arc::clone(&self.func).with_new_children(children)?;
216        Ok(Arc::new(AsyncFuncExpr {
217            name: self.name.clone(),
218            func: new_func,
219            return_field: Arc::clone(&self.return_field),
220        }))
221    }
222
223    fn fmt_sql(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
224        write!(f, "{}", self.func)
225    }
226}