Skip to main content

vortex_array/scalar_fn/builtin/fill_null/
kernel.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use vortex_error::VortexExpect;
5use vortex_error::VortexResult;
6use vortex_error::vortex_ensure;
7
8use crate::ArrayRef;
9use crate::ExecutionCtx;
10use crate::IntoArray;
11use crate::array::ArrayView;
12use crate::array::VTable;
13use crate::arrays::Constant;
14use crate::arrays::ConstantArray;
15use crate::arrays::ScalarFn;
16use crate::arrays::scalar_fn::ExactScalarFn;
17use crate::arrays::scalar_fn::ScalarFnArrayExt;
18use crate::arrays::scalar_fn::ScalarFnArrayView;
19use crate::builtins::ArrayBuiltins;
20use crate::kernel::ExecuteParentKernel;
21use crate::optimizer::rules::ArrayParentReduceRule;
22use crate::scalar::Scalar;
23use crate::scalar_fn::builtin::fill_null::FillNull as FillNullExpr;
24use crate::validity::Validity;
25
26/// Fill nulls in an array with a scalar value without reading buffers.
27///
28/// This trait is for fill_null implementations that can operate purely on array metadata
29/// and structure without needing to read or execute on the underlying buffers.
30/// Implementations should return `None` if the operation requires buffer access.
31///
32/// # Preconditions
33///
34/// The fill value is guaranteed to be non-null. The array is guaranteed to have mixed
35/// validity (neither all-valid nor all-invalid).
36pub trait FillNullReduce: VTable {
37    fn fill_null(array: ArrayView<'_, Self>, fill_value: &Scalar)
38    -> VortexResult<Option<ArrayRef>>;
39}
40
41/// Fill nulls in an array with a scalar value, potentially reading buffers.
42///
43/// Unlike [`FillNullReduce`], this trait is for fill_null implementations that may need
44/// to read and execute on the underlying buffers to produce the result.
45///
46/// # Preconditions
47///
48/// The fill value is guaranteed to be non-null. The array is guaranteed to have mixed
49/// validity (neither all-valid nor all-invalid).
50pub trait FillNullKernel: VTable {
51    fn fill_null(
52        array: ArrayView<'_, Self>,
53        fill_value: &Scalar,
54        ctx: &mut ExecutionCtx,
55    ) -> VortexResult<Option<ArrayRef>>;
56}
57
58/// Short-circuits fill_null for the inputs that need no encoding-specific work.
59///
60/// Returns `Some(result)` when the answer is already known, or `None` when fill_null must proceed
61/// with the encoding-specific implementation. Kernels can therefore rely on a non-null fill value.
62///
63/// The result can be a lazy [`ScalarFn`] array, so a caller that needs a computed array
64/// **must** execute it.
65///
66/// [`ScalarFn`]: crate::arrays::ScalarFn
67pub fn short_circuit(array: &ArrayRef, fill_value: &Scalar) -> VortexResult<Option<ArrayRef>> {
68    vortex_ensure!(
69        !fill_value.is_null(),
70        "fill_null requires a non-null fill value"
71    );
72
73    // If the array has no nulls, fill_null is a no-op (just cast for nullability).
74    if !array.dtype().is_nullable()
75        || matches!(
76            array.validity()?,
77            Validity::NonNullable | Validity::AllValid
78        )
79    {
80        return array.clone().cast(fill_value.dtype().clone()).map(Some);
81    }
82
83    // If all values are null, replace the entire array with the fill value.
84    if array.validity()?.definitely_all_null() {
85        return Ok(Some(
86            ConstantArray::new(fill_value.clone(), array.len()).into_array(),
87        ));
88    }
89
90    Ok(None)
91}
92
93/// Fill null on a [`ConstantArray`] by replacing null scalars with the fill value,
94/// or casting non-null scalars to the fill value's dtype.
95pub(crate) fn fill_null_constant(
96    array: ArrayView<Constant>,
97    fill_value: &Scalar,
98) -> VortexResult<ArrayRef> {
99    let scalar = if array.scalar().is_null() {
100        fill_value.clone()
101    } else {
102        array.scalar().cast(fill_value.dtype())?
103    };
104    Ok(ConstantArray::new(scalar, array.len()).into_array())
105}
106
107/// Adaptor that wraps a [`FillNullReduce`] impl as an [`ArrayParentReduceRule`].
108#[derive(Default, Debug)]
109pub struct FillNullReduceAdaptor<V>(pub V);
110
111impl<V> ArrayParentReduceRule<V> for FillNullReduceAdaptor<V>
112where
113    V: FillNullReduce,
114{
115    type Parent = ExactScalarFn<FillNullExpr>;
116
117    fn reduce_parent(
118        &self,
119        array: ArrayView<'_, V>,
120        parent: ScalarFnArrayView<'_, FillNullExpr>,
121        child_idx: usize,
122    ) -> VortexResult<Option<ArrayRef>> {
123        // Only process the input child (index 0), not the fill_value child (index 1).
124        if child_idx != 0 {
125            return Ok(None);
126        }
127        let scalar_fn_array = parent
128            .as_opt::<ScalarFn>()
129            .vortex_expect("ExactScalarFn matcher confirmed ScalarFnArray");
130        // A non-constant fill is left for `FillNull::execute`, which materializes lazy scalars.
131        let Some(fill_value) = scalar_fn_array.get_child(1).as_constant() else {
132            return Ok(None);
133        };
134        let arr = array.array().clone();
135        if let Some(result) = short_circuit(&arr, fill_value)? {
136            return Ok(Some(result));
137        }
138        <V as FillNullReduce>::fill_null(array, fill_value)
139    }
140}
141
142/// Adaptor that wraps a [`FillNullKernel`] impl as an [`ExecuteParentKernel`].
143#[derive(Default, Debug)]
144pub struct FillNullExecuteAdaptor<V>(pub V);
145
146impl<V> ExecuteParentKernel<V> for FillNullExecuteAdaptor<V>
147where
148    V: FillNullKernel,
149{
150    type Parent = ExactScalarFn<FillNullExpr>;
151
152    fn execute_parent(
153        &self,
154        array: ArrayView<'_, V>,
155        parent: ScalarFnArrayView<'_, FillNullExpr>,
156        child_idx: usize,
157        ctx: &mut ExecutionCtx,
158    ) -> VortexResult<Option<ArrayRef>> {
159        // Only process the input child (index 0), not the fill_value child (index 1).
160        if child_idx != 0 {
161            return Ok(None);
162        }
163        let scalar_fn_array = parent
164            .as_opt::<ScalarFn>()
165            .vortex_expect("ExactScalarFn matcher confirmed ScalarFnArray");
166        // A non-constant fill is left for `FillNull::execute`, which materializes lazy scalars.
167        let Some(fill_value) = scalar_fn_array.get_child(1).as_constant() else {
168            return Ok(None);
169        };
170        let arr = array.array().clone();
171        if let Some(result) = short_circuit(&arr, fill_value)? {
172            return Ok(Some(result));
173        }
174        <V as FillNullKernel>::fill_null(array, fill_value, ctx)
175    }
176}