Skip to content
Open
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
33 changes: 33 additions & 0 deletions datafusion/ffi/integration-tests/tests/cases/udf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ mod tests {
use datafusion::logical_expr::{ExpressionPlacement, ScalarUDF, ScalarUDFImpl};
use datafusion::prelude::{SessionContext, col};
use datafusion_execution::config::SessionConfig;
use datafusion_expr::interval_arithmetic::Interval;
use datafusion_expr::lit;
use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
use datafusion_ffi::tests::create_record_batch;
Expand Down Expand Up @@ -124,6 +125,38 @@ mod tests {
"output_ordering requires exactly one input"
);

let parent = Interval::make(Some(2_i64), Some(8_i64))?;
let input_a = Interval::make(Some(0_i64), Some(5_i64))?;
let input_b = Interval::make(Some(4_i64), Some(10_i64))?;
let expected_a = Interval::make(Some(2_i64), Some(5_i64))?;
let expected_b = Interval::make(Some(4_i64), Some(8_i64))?;

assert_eq!(
foreign_func.propagate_constraints(&parent, &[&input_a, &input_b])?,
Some(vec![expected_a, expected_b])
);

let upper_only = Interval::make(None, Some(8_i64))?;
let lower_only = Interval::make(Some(2_i64), None)?;
assert_eq!(
foreign_func.propagate_constraints(&upper_only, &[&lower_only])?,
Some(vec![parent.clone()])
);

let disjoint_parent = Interval::make(Some(10_i64), Some(20_i64))?;
assert_eq!(
foreign_func.propagate_constraints(&disjoint_parent, &[&input_a])?,
None
);
assert!(foreign_func.propagate_constraints(&parent, &[]).is_err());

let ffi_abs_func = (module.create_scalar_udf)();
let foreign_abs_func: Arc<dyn ScalarUDFImpl> = (&ffi_abs_func).into();
assert_eq!(
foreign_abs_func.propagate_constraints(&parent, &[&input_a])?,
Some(vec![])
);

Ok(())
}

Expand Down
23 changes: 23 additions & 0 deletions datafusion/ffi/src/tests/udf_udaf_udwf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use arrow_schema::DataType;
use datafusion_catalog::TableFunctionImpl;
use datafusion_common::ScalarValue;
use datafusion_common::config::ConfigOptions;
use datafusion_expr::interval_arithmetic::Interval;
use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
use datafusion_expr::{
AggregateUDF, ColumnarValue, ExpressionPlacement, ScalarFunctionArgs, ScalarUDF,
Expand Down Expand Up @@ -176,6 +177,28 @@ impl ScalarUDFImpl for PlacementUDF {
),
}
}

fn propagate_constraints(
&self,
interval: &Interval,
inputs: &[&Interval],
) -> datafusion_common::Result<Option<Vec<Interval>>> {
if inputs.is_empty() {
return datafusion_common::internal_err!(
"propagate_constraints requires at least one input"
);
}

let mut propagated = Vec::with_capacity(inputs.len());
for input in inputs {
match input.intersect(interval)? {
Some(narrowed) => propagated.push(narrowed),
None => return Ok(None),
}
}

Ok(Some(propagated))
}
}

pub(crate) extern "C" fn create_placement_func() -> FFI_ScalarUDF {
Expand Down
150 changes: 150 additions & 0 deletions datafusion/ffi/src/udf/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use arrow::ffi::{FFI_ArrowSchema, from_ffi, to_ffi};
use arrow_schema::FieldRef;
use datafusion_common::config::ConfigOptions;
use datafusion_common::{DataFusionError, Result, internal_err};
use datafusion_expr::interval_arithmetic::Interval;
use datafusion_expr::sort_properties::{ExprProperties, SortProperties};
use datafusion_expr::type_coercion::functions::fields_with_udf;
use datafusion_expr::{
Expand All @@ -30,6 +31,7 @@ use crate::arrow_wrappers::{WrappedArray, WrappedSchema};
use crate::config::FFI_ConfigOptions;
use crate::expr::columnar_value::FFI_ColumnarValue;
use crate::expr::expr_properties::{FFI_ExprProperties, FFI_SortProperties};
use crate::expr::interval::FFI_Interval;
use crate::placement::FFI_ExpressionPlacement;
use crate::util::{
FFI_Option, FFI_Result, rvec_wrapped_to_vec_datatype, vec_datatype_to_rvec_wrapped,
Expand Down Expand Up @@ -123,6 +125,14 @@ pub struct FFI_ScalarUDF {
udf: &Self,
inputs: SVec<FFI_ExprProperties>,
) -> FFI_Result<FFI_SortProperties>,

/// FFI equivalent to [`ScalarUDFImpl::propagate_constraints`].
pub propagate_constraints:
unsafe extern "C" fn(
udf: &Self,
interval: FFI_Interval,
inputs: SVec<FFI_Interval>,
) -> FFI_Result<FFI_Option<SVec<FFI_Interval>>>,
}

unsafe impl Send for FFI_ScalarUDF {}
Expand Down Expand Up @@ -228,6 +238,38 @@ unsafe extern "C" fn with_updated_config_fn_wrapper(
FFI_Result::Ok(updated.into())
}

unsafe extern "C" fn propagate_constraints_fn_wrapper(
udf: &FFI_ScalarUDF,
interval: FFI_Interval,
inputs: SVec<FFI_Interval>,
) -> FFI_Result<FFI_Option<SVec<FFI_Interval>>> {
let interval = sresult_return!(Interval::try_from(interval));
let inputs = sresult_return!(
inputs
.into_iter()
.map(Interval::try_from)
.collect::<Result<Vec<_>>>()
);
let input_refs = inputs.iter().collect::<Vec<_>>();

let result = udf
.inner()
.propagate_constraints(&interval, &input_refs)
.and_then(|maybe_intervals| {
maybe_intervals
.map(|intervals| {
intervals
.into_iter()
.map(FFI_Interval::try_from)
.collect::<Result<SVec<_>>>()
})
.transpose()
})
.map(FFI_Option::from);

sresult!(result)
}

unsafe extern "C" fn invoke_with_args_fn_wrapper(
udf: &FFI_ScalarUDF,
args: SVec<WrappedArray>,
Expand Down Expand Up @@ -329,6 +371,7 @@ impl From<Arc<ScalarUDF>> for FFI_ScalarUDF {
preserves_lex_ordering: preserves_lex_ordering_fn_wrapper,
with_updated_config: with_updated_config_fn_wrapper,
output_ordering: output_ordering_fn_wrapper,
propagate_constraints: propagate_constraints_fn_wrapper,
}
}
}
Expand Down Expand Up @@ -567,6 +610,31 @@ impl ScalarUDFImpl for ForeignScalarUDF {

df_result!(result).map(|ordering| SortProperties::from(&ordering))
}

fn propagate_constraints(
&self,
interval: &Interval,
inputs: &[&Interval],
) -> Result<Option<Vec<Interval>>> {
let interval = FFI_Interval::try_from(interval)?;
let inputs = inputs
.iter()
.map(|input| FFI_Interval::try_from(*input))
.collect::<Result<SVec<_>>>()?;

let result =
unsafe { (self.udf.propagate_constraints)(&self.udf, interval, inputs) };

df_result!(result)?
.into_option()
.map(|intervals| {
intervals
.into_iter()
.map(Interval::try_from)
.collect::<Result<Vec<_>>>()
})
.transpose()
}
}

#[cfg(test)]
Expand Down Expand Up @@ -630,6 +698,30 @@ mod tests {
signature: self.signature.clone(),
}))
}

fn propagate_constraints(
&self,
interval: &Interval,
inputs: &[&Interval],
) -> Result<Option<Vec<Interval>>> {
if inputs.is_empty() {
return internal_err!(
"propagate_constraints requires at least one input"
);
}

// Intersect each input with the parent interval so tests catch
// dropped, reordered, or mutated bounds as well as `Ok(None)`.
let mut propagated = Vec::with_capacity(inputs.len());
for input in inputs {
match input.intersect(interval)? {
Some(narrowed) => propagated.push(narrowed),
None => return Ok(None),
}
}

Ok(Some(propagated))
}
}

#[test]
Expand All @@ -648,6 +740,11 @@ mod tests {
.with_updated_config(&ConfigOptions::default())
.is_none()
);
let interval = Interval::make(Some(1_i64), Some(10_i64))?;
assert_eq!(
foreign_udf.propagate_constraints(&interval, &[&interval])?,
Some(vec![])
);

Ok(())
}
Expand Down Expand Up @@ -792,4 +889,57 @@ mod tests {

Ok(())
}

#[test]
fn test_ffi_udf_propagate_constraints_round_trip() -> Result<()> {
use datafusion_expr::Volatility;

let original_udf = Arc::new(ScalarUDF::from(PlacementUDF {
signature: Signature::uniform(
1,
vec![DataType::Int64],
Volatility::Immutable,
),
}));
let mut ffi_udf = FFI_ScalarUDF::from(original_udf);

let local_udf: Arc<dyn ScalarUDFImpl> = (&ffi_udf).into();
assert!(local_udf.is::<PlacementUDF>());

ffi_udf.library_marker_id = crate::mock_foreign_marker_id;
let foreign_udf: Arc<dyn ScalarUDFImpl> = (&ffi_udf).into();
assert!(foreign_udf.is::<ForeignScalarUDF>());

let parent = Interval::make(Some(2_i64), Some(8_i64))?;
let input_a = Interval::make(Some(0_i64), Some(5_i64))?;
let input_b = Interval::make(Some(4_i64), Some(10_i64))?;
let expected_a = Interval::make(Some(2_i64), Some(5_i64))?;
let expected_b = Interval::make(Some(4_i64), Some(8_i64))?;

let upper_only = Interval::make(None, Some(8_i64))?;
let lower_only = Interval::make(Some(2_i64), None)?;
let disjoint_parent = Interval::make(Some(10_i64), Some(20_i64))?;

for udf in [local_udf, foreign_udf] {
// Tightened multi-input intervals in order
assert_eq!(
udf.propagate_constraints(&parent, &[&input_a, &input_b])?,
Some(vec![expected_a.clone(), expected_b.clone()])
);
// Open-ended (unbounded) intervals round-trip cleanly
assert_eq!(
udf.propagate_constraints(&upper_only, &[&lower_only])?,
Some(vec![parent.clone()])
);
// Infeasible constraints return Ok(None)
assert_eq!(
udf.propagate_constraints(&disjoint_parent, &[&input_a])?,
None
);
// Errors propagate across FFI
assert!(udf.propagate_constraints(&parent, &[]).is_err());
}

Ok(())
}
}