Skip to main content

vortex_array/scalar_fn/builtin/fill_null/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod kernel;
5
6pub use kernel::*;
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure;
10use vortex_error::vortex_err;
11use vortex_session::VortexSession;
12use vortex_session::registry::CachedId;
13
14use crate::AnyColumnar;
15use crate::ArrayRef;
16use crate::Canonical;
17use crate::CanonicalView;
18use crate::ColumnarView;
19use crate::ExecutionCtx;
20use crate::IntoArray;
21use crate::arrays::Bool;
22use crate::arrays::Constant;
23use crate::arrays::Decimal;
24use crate::arrays::Extension;
25use crate::arrays::Primitive;
26use crate::arrays::ScalarFnArray;
27use crate::arrays::VarBinView;
28use crate::dtype::DType;
29use crate::optimizer::ArrayOptimizer;
30use crate::require_input;
31use crate::scalar::Scalar;
32use crate::scalar_fn::Arity;
33use crate::scalar_fn::ChildName;
34use crate::scalar_fn::EmptyOptions;
35use crate::scalar_fn::ExecutionArgs;
36use crate::scalar_fn::ReduceNode;
37use crate::scalar_fn::ReduceNodeValidity;
38use crate::scalar_fn::ScalarFnExecutionResult;
39use crate::scalar_fn::ScalarFnId;
40use crate::scalar_fn::ScalarFnVTable;
41use crate::scalar_fn::ScalarFnVTableExt;
42use crate::scalar_fn::is_not_null_node;
43
44/// An expression that replaces null values in the input with a fill value.
45#[derive(Clone)]
46pub struct FillNull;
47
48impl FillNull {
49    /// Creates a lazy operation that replaces null input values with `fill_value`.
50    ///
51    /// # Errors
52    ///
53    /// Returns an error if the children have different lengths or incompatible dtypes.
54    pub fn try_new(input: ArrayRef, fill_value: ArrayRef) -> VortexResult<ScalarFnArray> {
55        ScalarFnArray::try_new(FillNull.bind(EmptyOptions), [input, fill_value])
56    }
57
58    pub(crate) fn output_dtype(input: &DType, fill_value: &DType) -> VortexResult<DType> {
59        vortex_ensure!(
60            input.eq_ignore_nullability(fill_value),
61            "fill_null requires input and fill value to have the same base type, got {input} and {fill_value}"
62        );
63
64        Ok(input.with_nullability(fill_value.nullability()))
65    }
66
67    /// Returns whether fill_null can execute inputs of `dtype`.
68    ///
69    /// These are the dtypes that `fill_null_canonical` and the `vortex-functions` fill_null
70    /// kernels can fill, so update this function whenever they gain or lose one. Rewrites into
71    /// fill_null, such as the CASE WHEN simplification, check it first because other dtypes fail
72    /// at execution time.
73    ///
74    /// A null dtype has no non-null fill value. Union and variant values have no zip, so any dtype
75    /// that contains one of them is rejected, even where its fill does not zip those values.
76    pub fn supports_dtype(dtype: &DType) -> bool {
77        !matches!(dtype, DType::Null) && !contains_union_or_variant(dtype)
78    }
79}
80
81impl ScalarFnVTable for FillNull {
82    type Options = EmptyOptions;
83
84    fn id(&self) -> ScalarFnId {
85        static ID: CachedId = CachedId::new("vortex.fill_null");
86        *ID
87    }
88
89    fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
90        Ok(Some(vec![]))
91    }
92
93    fn deserialize(
94        &self,
95        _metadata: &[u8],
96        _session: &VortexSession,
97    ) -> VortexResult<Self::Options> {
98        Ok(EmptyOptions)
99    }
100
101    fn arity(&self, _options: &Self::Options) -> Arity {
102        Arity::Exact(2)
103    }
104
105    fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
106        match child_idx {
107            0 => ChildName::from("input"),
108            1 => ChildName::from("fill_value"),
109            _ => unreachable!("Invalid child index {} for FillNull expression", child_idx),
110        }
111    }
112
113    fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
114        Self::output_dtype(&arg_dtypes[0], &arg_dtypes[1])
115    }
116
117    fn execute(
118        &self,
119        _options: &Self::Options,
120        args: &dyn ExecutionArgs,
121        ctx: &mut ExecutionCtx,
122    ) -> VortexResult<ArrayRef> {
123        let input = args.get(0)?;
124        let fill_value = args.get(1)?;
125        // Parent kernels decline a fill that is not already constant. Materialize it here so a
126        // lazy scalar, such as a literal `ScalarFnArray`, can still fill nulls.
127        let fill_was_lazy = !fill_value.is::<Constant>();
128        let fill_value = if fill_was_lazy {
129            fill_value.execute_until::<Constant>(ctx)?
130        } else {
131            fill_value
132        };
133
134        let Some(fill_scalar) = fill_value.as_constant() else {
135            // Slicing a constant fill to an empty range yields an empty canonical array rather
136            // than a constant. An empty input has no nulls to fill, so there is nothing to do.
137            vortex_ensure!(
138                input.is_empty(),
139                "fill_null fill_value must be a constant/scalar"
140            );
141            let dtype = input
142                .dtype()
143                .with_nullability(fill_value.dtype().nullability());
144            return Ok(Canonical::empty(&dtype).into_array());
145        };
146
147        vortex_ensure!(
148            !fill_scalar.is_null(),
149            "fill_null requires a non-null fill value"
150        );
151
152        if fill_was_lazy {
153            // Hand the rebuilt node back with a constant fill so the input's FillNull
154            // kernels (including those registered by vortex-functions) get a chance.
155            return FillNull::try_new(input, fill_value)?
156                .into_array()
157                .optimize_ctx(ctx);
158        }
159
160        let Some(columnar) = input.as_opt::<AnyColumnar>() else {
161            let input = input.execute::<ArrayRef>(ctx)?;
162            return Ok(FillNull::try_new(input, fill_value)?.into_array());
163        };
164
165        match columnar {
166            ColumnarView::Canonical(canonical) => fill_null_canonical(canonical, fill_scalar, ctx),
167            ColumnarView::Constant(constant) => fill_null_constant(constant, fill_scalar),
168        }
169    }
170
171    fn execute_step(
172        &self,
173        options: &Self::Options,
174        args: &dyn ExecutionArgs,
175        ctx: &mut ExecutionCtx,
176    ) -> VortexResult<ScalarFnExecutionResult> {
177        // Only once the fill is constant: `execute` materializes a lazy fill first, so the input's
178        // FillNull kernels can still apply before the input is decoded.
179        if args.input_matches(1, |fill| fill.is::<Constant>())? {
180            require_input!(args, 0 => AnyColumnar);
181        }
182        self.execute(options, args, ctx)
183            .map(ScalarFnExecutionResult::done)
184    }
185
186    fn simplify<T: ReduceNode>(
187        &self,
188        _options: &Self::Options,
189        node: &T,
190    ) -> VortexResult<Option<T>> {
191        let child = node.child(0);
192        if !child.node_dtype()?.is_nullable() {
193            return Ok(Some(child));
194        }
195        Ok(None)
196    }
197
198    fn validity<T: ReduceNode>(
199        &self,
200        _options: &Self::Options,
201        node: &T,
202    ) -> VortexResult<ReduceNodeValidity<T>> {
203        // After fill_null, the result validity depends on the fill value's nullability.
204        // If fill_value is non-nullable, the result is always valid.
205        Ok(ReduceNodeValidity::Reduced(is_not_null_node(
206            &node.child(1),
207        )?))
208    }
209
210    fn is_strict(&self, _options: &Self::Options) -> bool {
211        // This function replaces null input values instead of propagating them.
212        false
213    }
214
215    fn is_infallible(&self, _options: &Self::Options) -> bool {
216        true
217    }
218}
219
220/// Returns whether `dtype` is or contains a union or a variant.
221fn contains_union_or_variant(dtype: &DType) -> bool {
222    match dtype {
223        DType::Union(..) | DType::Variant(_) => true,
224        DType::List(element, _) | DType::FixedSizeList(element, ..) => {
225            contains_union_or_variant(element)
226        }
227        DType::Map(map, _) => {
228            contains_union_or_variant(&map.key_dtype())
229                || contains_union_or_variant(&map.value_dtype())
230        }
231        DType::Struct(fields, _) => fields
232            .fields()
233            .any(|field| contains_union_or_variant(&field)),
234        DType::Extension(ext) => contains_union_or_variant(ext.storage_dtype()),
235        DType::Null
236        | DType::Bool(_)
237        | DType::Primitive(..)
238        | DType::Decimal(..)
239        | DType::Utf8(_)
240        | DType::Binary(_) => false,
241    }
242}
243
244/// Fill nulls on a canonical array by directly dispatching to the appropriate kernel.
245///
246/// Returns the filled array, or bails if the canonical type cannot be filled.
247fn fill_null_canonical(
248    canonical: CanonicalView<'_>,
249    fill_value: &Scalar,
250    ctx: &mut ExecutionCtx,
251) -> VortexResult<ArrayRef> {
252    let arr = canonical.to_array_ref();
253    if let Some(result) = short_circuit(&arr, fill_value)? {
254        return Ok(result);
255    }
256    if !FillNull::supports_dtype(arr.dtype()) {
257        vortex_bail!("fill_null is not supported for {} arrays", arr.dtype());
258    }
259    match canonical {
260        CanonicalView::Bool(a) => <Bool as FillNullKernel>::fill_null(a, fill_value, ctx)?
261            .ok_or_else(|| vortex_err!("FillNullKernel for BoolArray returned None")),
262        CanonicalView::Primitive(a) => {
263            <Primitive as FillNullKernel>::fill_null(a, fill_value, ctx)?
264                .ok_or_else(|| vortex_err!("FillNullKernel for PrimitiveArray returned None"))
265        }
266        CanonicalView::Decimal(a) => <Decimal as FillNullKernel>::fill_null(a, fill_value, ctx)?
267            .ok_or_else(|| vortex_err!("FillNullKernel for DecimalArray returned None")),
268        CanonicalView::VarBinView(a) => {
269            <VarBinView as FillNullKernel>::fill_null(a, fill_value, ctx)?
270                .ok_or_else(|| vortex_err!("FillNullKernel for VarBinViewArray returned None"))
271        }
272        CanonicalView::Extension(a) => {
273            <Extension as FillNullKernel>::fill_null(a, fill_value, ctx)?
274                .ok_or_else(|| vortex_err!("FillNullKernel for ExtensionArray returned None"))
275        }
276        CanonicalView::Struct(_)
277        | CanonicalView::List(_)
278        | CanonicalView::FixedSizeList(_)
279        | CanonicalView::Map(_) => {
280            vortex_bail!(
281                "fill_null for {} arrays requires vortex_functions::initialize",
282                arr.dtype()
283            )
284        }
285        CanonicalView::Null(_) | CanonicalView::Union(_) | CanonicalView::Variant(_) => {
286            vortex_bail!("fill_null is not supported for {} arrays", arr.dtype())
287        }
288    }
289}