Skip to main content

vortex_functions/list_transform/
mod.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4#[cfg(test)]
5mod tests;
6
7use std::fmt;
8use std::fmt::Display;
9use std::fmt::Formatter;
10use std::sync::Arc;
11
12use itertools::Itertools;
13use vortex_array::ArrayRef;
14use vortex_array::ExecutionCtx;
15use vortex_array::IntoArray;
16use vortex_array::arrays::List;
17use vortex_array::arrays::ListArray;
18use vortex_array::arrays::ListViewArray;
19use vortex_array::arrays::list::ListArrayExt;
20use vortex_array::arrays::list::ListArraySlotsExt;
21use vortex_array::arrays::listview::ListViewArrayExt;
22use vortex_array::arrays::listview::ListViewArraySlotsExt;
23use vortex_array::arrays::listview::ListViewRebuildMode;
24use vortex_array::dtype::DType;
25use vortex_array::dtype::FieldName;
26use vortex_array::scalar_fn::Arity;
27use vortex_array::scalar_fn::ChildName;
28use vortex_array::scalar_fn::ExecutionArgs;
29use vortex_array::scalar_fn::ReduceNode;
30use vortex_array::scalar_fn::ScalarFnId;
31use vortex_array::scalar_fn::ScalarFnVTable;
32use vortex_array::scalar_fn::ScalarFnVTableExt;
33use vortex_array::scalar_fn::display::ExprDisplay;
34use vortex_error::VortexResult;
35use vortex_error::vortex_bail;
36use vortex_error::vortex_ensure;
37use vortex_error::vortex_ensure_eq;
38use vortex_expr::BoundLambda;
39use vortex_expr::Lambda;
40use vortex_session::registry::CachedId;
41
42/// Apply a lambda to every element of each list, keeping each list's length and validity.
43///
44/// The lambda takes one parameter, the element. The only child is the list, of `List` dtype in any
45/// encoding, and the result is a `List` of the same shape. A lambda that can fail runs only on the
46/// elements of valid lists.
47#[derive(Clone)]
48pub struct ListTransform;
49
50/// The lambda of a [`ListTransform`], as written or bound to the element's dtype.
51#[derive(Clone, Debug, PartialEq, Eq, Hash)]
52pub enum ListTransformOptions {
53    /// The lambda as written, in an [`Expression`](vortex_expr::Expression).
54    Lambda(Lambda),
55    /// The lambda bound to the element's dtype, in a
56    /// [`BoundExpression`](vortex_array::expr::BoundExpression) or an array.
57    Bound(BoundLambda),
58}
59
60impl Display for ListTransformOptions {
61    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
62        match self {
63            Self::Lambda(lambda) => lambda.fmt(f),
64            Self::Bound(lambda) => lambda.fmt(f),
65        }
66    }
67}
68
69impl ScalarFnVTable for ListTransform {
70    type Options = ListTransformOptions;
71
72    fn id(&self) -> ScalarFnId {
73        static ID: CachedId = CachedId::new("vortex.list.transform");
74        *ID
75    }
76
77    fn arity(&self, _options: &ListTransformOptions) -> Arity {
78        Arity::Exact(1)
79    }
80
81    fn child_name(&self, _options: &ListTransformOptions, child_idx: usize) -> ChildName {
82        match child_idx {
83            0 => ChildName::from("list"),
84            _ => unreachable!("Invalid child index {child_idx} for list_transform()"),
85        }
86    }
87
88    fn fmt_sql(
89        &self,
90        options: &ListTransformOptions,
91        expr: &dyn ExprDisplay,
92        f: &mut Formatter<'_>,
93    ) -> fmt::Result {
94        write!(f, "{}({}, {options})", self.id(), expr.display_child(0))
95    }
96
97    fn return_dtype(&self, options: &ListTransformOptions, args: &[DType]) -> VortexResult<DType> {
98        let element = match options {
99            ListTransformOptions::Lambda(lambda) => {
100                lambda.return_dtype(&element_dtype(&args[0], lambda.params())?)?
101            }
102            ListTransformOptions::Bound(lambda) => {
103                check_bound_to(lambda, &args[0])?;
104                lambda.dtype().clone()
105            }
106        };
107        Ok(DType::List(Arc::new(element), args[0].nullability()))
108    }
109
110    fn bind_options(
111        &self,
112        options: &ListTransformOptions,
113        args: &[DType],
114    ) -> VortexResult<Option<ListTransformOptions>> {
115        match options {
116            ListTransformOptions::Lambda(lambda) => {
117                let element = element_dtype(&args[0], lambda.params())?;
118                Ok(Some(ListTransformOptions::Bound(lambda.bind(&element)?)))
119            }
120            ListTransformOptions::Bound(lambda) => {
121                check_bound_to(lambda, &args[0])?;
122                Ok(None)
123            }
124        }
125    }
126
127    fn execute(
128        &self,
129        options: &ListTransformOptions,
130        args: &dyn ExecutionArgs,
131        ctx: &mut ExecutionCtx,
132    ) -> VortexResult<ArrayRef> {
133        let ListTransformOptions::Bound(lambda) = options else {
134            vortex_bail!("list_transform()'s lambda is not bound");
135        };
136        match args.get(0)?.try_downcast::<List>() {
137            Ok(list) => transform_list(list, lambda, ctx),
138            Err(list) => transform_list_view(list.execute::<ListViewArray>(ctx)?, lambda, ctx),
139        }
140    }
141
142    /// `transform(transform(l, f), g) -> transform(l, x -> g(f(x)))`
143    fn reduce<T: ReduceNode>(
144        &self,
145        options: &ListTransformOptions,
146        node: &T,
147    ) -> VortexResult<Option<T>> {
148        let ListTransformOptions::Bound(outer) = options else {
149            return Ok(None);
150        };
151        let inner_node = node.child(0);
152        let Some(ListTransformOptions::Bound(inner)) = inner_node
153            .scalar_fn()
154            .and_then(|scalar_fn| scalar_fn.as_opt::<ListTransform>())
155        else {
156            return Ok(None);
157        };
158        let Some(composed) = compose(outer, inner)? else {
159            return Ok(None);
160        };
161        let composed = ListTransform.bind(ListTransformOptions::Bound(composed));
162        Ok(Some(node.new_node(composed, &[inner_node.child(0)])?))
163    }
164
165    fn is_strict(&self, _options: &ListTransformOptions) -> bool {
166        true
167    }
168
169    fn is_infallible(&self, options: &ListTransformOptions) -> bool {
170        match options {
171            ListTransformOptions::Lambda(lambda) => lambda.is_infallible(),
172            ListTransformOptions::Bound(lambda) => lambda.is_infallible(),
173        }
174    }
175}
176
177/// `(x) -> outer(inner(x))`, unless that would compute `inner` more than once or drop its failures.
178fn compose(outer: &BoundLambda, inner: &BoundLambda) -> VortexResult<Option<BoundLambda>> {
179    match outer.param_reads() {
180        0 if inner.is_infallible() => {}
181        1 => {}
182        _ => return Ok(None),
183    }
184    outer.compose(inner)
185}
186
187/// Check that a bound lambda's parameter has the element dtype of a list of this dtype.
188fn check_bound_to(lambda: &BoundLambda, list: &DType) -> VortexResult<()> {
189    let element = element_dtype(list, lambda.params().names().as_ref())?;
190    vortex_ensure!(
191        lambda.is_bound_to(&element),
192        "list_transform()'s lambda {lambda} is bound to element dtype {}, not {}",
193        lambda.params().fields().format(", "),
194        element[0]
195    );
196    Ok(())
197}
198
199/// The dtype of the lambda's one parameter, the element, for a list of this dtype.
200fn element_dtype(list: &DType, params: &[FieldName]) -> VortexResult<[DType; 1]> {
201    let DType::List(element, _) = list else {
202        vortex_bail!("list_transform() takes a List, got {list}");
203    };
204    vortex_ensure!(
205        params.len() == 1,
206        "list_transform() takes a lambda of one parameter, the element, not ({})",
207        params.iter().format(", ")
208    );
209    Ok([element.as_ref().clone()])
210}
211
212/// The lambda over a list's elements, inside the list's offsets and validity.
213///
214/// A lambda that can fail runs only on the elements valid lists reference. One that can't runs on
215/// every element from the first list to the last: results under null lists are never read.
216fn transform_list(
217    list: ListArray,
218    lambda: &BoundLambda,
219    ctx: &mut ExecutionCtx,
220) -> VortexResult<ArrayRef> {
221    let list = if lambda.is_infallible() {
222        trim_ends(list, ctx)?
223    } else {
224        list.compact(ctx)?
225    };
226    let values = lambda.evaluate(vec![list.elements().clone()], list.elements().len())?;
227    vortex_ensure_eq!(values.len(), list.elements().len());
228    // SAFETY: the offsets and validity are the list's, over one value per element.
229    Ok(
230        unsafe { ListArray::new_unchecked(values, list.offsets().clone(), list.list_validity()) }
231            .into_array(),
232    )
233}
234
235/// The lambda over a list view's elements, inside the view's offsets, sizes and validity.
236///
237/// A lambda that can fail runs only on the elements valid lists reference.
238fn transform_list_view(
239    view: ListViewArray,
240    lambda: &BoundLambda,
241    ctx: &mut ExecutionCtx,
242) -> VortexResult<ArrayRef> {
243    let view = if lambda.is_infallible() {
244        view
245    } else {
246        view.rebuild(ListViewRebuildMode::MakeExactWithEmptyNulls, ctx)?
247    };
248    let values = lambda.evaluate(vec![view.elements().clone()], view.elements().len())?;
249    vortex_ensure_eq!(values.len(), view.elements().len());
250    // SAFETY: the offsets, sizes and validity are the view's, over one value per element, so the
251    // views keep their bounds and their layout.
252    Ok(unsafe {
253        ListViewArray::new_unchecked(
254            values,
255            view.offsets().clone(),
256            view.sizes().clone(),
257            view.listview_validity(),
258        )
259        .with_zero_copy_to_list(view.is_zero_copy_to_list())
260    }
261    .into_array())
262}
263
264/// The list without what comes before its first list and after its last.
265fn trim_ends(list: ListArray, ctx: &mut ExecutionCtx) -> VortexResult<ListArray> {
266    if list.offset_at(0, ctx)? == 0 && list.offset_at(list.len(), ctx)? == list.elements().len() {
267        return Ok(list);
268    }
269    list.reset_offsets(false, ctx)
270}