Skip to main content

vortex_functions/list_contains/prepared/
data.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Debug;
5use std::fmt::Display;
6use std::fmt::Formatter;
7use std::hash::Hash;
8use std::hash::Hasher;
9use std::sync::Arc;
10use std::sync::OnceLock;
11
12use vortex_array::ArrayRef;
13use vortex_array::ExecutionCtx;
14use vortex_array::IntoArray;
15use vortex_array::arrays::ConstantArray;
16use vortex_array::arrays::ListViewArray;
17use vortex_array::arrays::listview::ListViewArraySlotsExt;
18use vortex_array::dtype::DType;
19use vortex_array::scalar::Scalar;
20use vortex_array::scalar_fn::ScalarFnRef;
21use vortex_array::scalar_fn::ScalarFnVTableExt;
22use vortex_array::scalar_fn::builtin::literal::Literal;
23use vortex_array::validity::Validity;
24use vortex_buffer::BitBuffer;
25use vortex_error::SharedVortexResult;
26use vortex_error::VortexResult;
27use vortex_error::vortex_bail;
28use vortex_error::vortex_ensure;
29use vortex_error::vortex_panic;
30
31use crate::list_contains::ListContainsOptions;
32use crate::list_contains::haystack::ArrayHaystack;
33
34/// The options of a [`PreparedSet`]: the list that every row holds, and its set.
35///
36/// The set is shared by every clone, so every batch a [`PreparedSet`] is applied to, and every
37/// slice or filter of the array it gives, looks up needles in the one set. The haystack needs
38/// an [`ExecutionCtx`] to materialize the elements, so it is built on the first lookup.
39///
40/// [`PreparedSet`]: crate::list_contains::PreparedSet
41#[derive(Clone)]
42pub struct PreparedSetData(Arc<SharedSet>);
43
44struct SharedSet {
45    /// The [`Literal`] of the non-null list that every row holds, shared with the expression it
46    /// came from rather than cloned out of it.
47    literal: ScalarFnRef,
48    /// Whether the list holds a null element, which the haystack does not hold.
49    has_null_element: bool,
50    /// Whether the list holds no element at all, counting null elements.
51    is_empty: bool,
52    /// The elements, and the haystack of the non-null ones, built on the first lookup.
53    set: OnceLock<SharedVortexResult<ElementSet>>,
54}
55
56/// The elements of the list, and their haystack.
57struct ElementSet {
58    /// All elements of the list, null elements included, with the element dtype of the list.
59    elements: ArrayRef,
60    haystack: ArrayHaystack,
61}
62
63impl ElementSet {
64    fn try_new(list: &Scalar, ctx: &mut ExecutionCtx) -> VortexResult<Self> {
65        // The canonical form of a constant list holds its elements once, whatever its length.
66        let elements = ConstantArray::new(list.clone(), 1)
67            .into_array()
68            .execute::<ListViewArray>(ctx)?
69            .elements()
70            .clone();
71        let haystack = ArrayHaystack::try_new(&elements, ctx)?;
72
73        Ok(Self { elements, haystack })
74    }
75}
76
77impl PreparedSetData {
78    /// Prepares the non-null list scalar `list` as a set.
79    ///
80    /// # Errors
81    ///
82    /// Fails when `list` is not a list, or is null.
83    pub fn try_new(list: Scalar) -> VortexResult<Self> {
84        Self::try_from_literal(Literal.bind(list))
85    }
86
87    /// Prepares the non-null list that the [`Literal`] `literal` holds as a set, sharing the
88    /// literal rather than cloning its list.
89    ///
90    /// # Errors
91    ///
92    /// Fails when `literal` is not a literal, or holds a null, or a value that is not a list.
93    pub(crate) fn try_from_literal(literal: ScalarFnRef) -> VortexResult<Self> {
94        let (has_null_element, is_empty) = {
95            let Some(list) = literal.as_opt::<Literal>() else {
96                vortex_bail!("A prepared set needs a literal list");
97            };
98            vortex_ensure!(
99                matches!(list.dtype(), DType::List(..)),
100                "A prepared set needs a list, got {}",
101                list.dtype()
102            );
103            let Some(elements) = list.as_list().element_values() else {
104                vortex_bail!("A prepared set needs a non-null list");
105            };
106            (elements.iter().any(Option::is_none), elements.is_empty())
107        };
108
109        Ok(Self(Arc::new(SharedSet {
110            literal,
111            has_null_element,
112            is_empty,
113            set: OnceLock::new(),
114        })))
115    }
116
117    /// Whether `other` shares this set rather than preparing its own.
118    #[cfg(test)]
119    pub(super) fn shares_set_with(&self, other: &Self) -> bool {
120        Arc::ptr_eq(&self.0, &other.0)
121    }
122
123    /// Whether the list holds no element at all, null elements included.
124    pub fn is_empty(&self) -> bool {
125        self.0.is_empty
126    }
127
128    /// The list that every row holds.
129    pub fn list(&self) -> &Scalar {
130        self.0.literal.as_::<Literal>()
131    }
132
133    /// The elements of the list, one row each, null elements included.
134    ///
135    /// # Errors
136    ///
137    /// Fails when the elements cannot be executed into the haystack.
138    pub fn elements(&self, ctx: &mut ExecutionCtx) -> VortexResult<&ArrayRef> {
139        Ok(&self.element_set(ctx)?.elements)
140    }
141
142    /// The elements and their haystack, built on the first call and shared after it.
143    fn element_set<'a>(&'a self, ctx: &mut ExecutionCtx) -> VortexResult<&'a ElementSet> {
144        self.0
145            .set
146            .get_or_init(|| ElementSet::try_new(self.list(), ctx).map_err(Arc::new))
147            .as_ref()
148            .map_err(|err| Arc::clone(err).into())
149    }
150
151    /// The dtype of the list that every row holds.
152    fn list_dtype(&self) -> &DType {
153        self.list().dtype()
154    }
155
156    /// The dtype of the list's elements.
157    fn element_dtype(&self) -> &DType {
158        let DType::List(element_dtype, _) = self.list_dtype() else {
159            vortex_panic!("A prepared set always holds a list");
160        };
161        element_dtype
162    }
163
164    /// Whether each of `needles` is an element of the list, under `options`.
165    ///
166    /// The needles must have the dtype of the list's elements, ignoring nullability. The result
167    /// has one row per needle, and the nullability that [`ListContainsOptions::result_nullability`]
168    /// declares. A null needle gives `null`. The exception is an empty list off SQL null
169    /// semantics, which gives `false` for every needle. Under SQL null semantics, a list that holds
170    /// a null element gives `null` for a needle that matches no element.
171    ///
172    /// A constant needle is looked up once, and gives a constant result.
173    ///
174    /// # Errors
175    ///
176    /// Fails when the needles do not have the dtype of the list's elements.
177    pub fn contains(
178        &self,
179        needles: &ArrayRef,
180        options: &ListContainsOptions,
181        ctx: &mut ExecutionCtx,
182    ) -> VortexResult<ArrayRef> {
183        if let Some(needle) = needles.as_constant() {
184            let result = self.contains_scalar(needle, options, ctx)?;
185            return Ok(ConstantArray::new(result, needles.len()).into_array());
186        }
187
188        self.check_needle_dtype(needles.dtype())?;
189        let (bits, needle_validity) = self.element_set(ctx)?.haystack.contains(needles, ctx)?;
190        self.result_from_bits(bits, needle_validity, needles.dtype(), options)
191    }
192
193    /// Whether the constant `needle` is an element of the list, under `options`.
194    ///
195    /// The answer is the one [`Self::contains`] gives for each row of a needle with this value, for
196    /// example for the fill value of a sparse needle. The haystack looks up one row.
197    ///
198    /// # Errors
199    ///
200    /// Fails when the needle does not have the dtype of the list's elements.
201    pub fn contains_scalar(
202        &self,
203        needle: &Scalar,
204        options: &ListContainsOptions,
205        ctx: &mut ExecutionCtx,
206    ) -> VortexResult<Scalar> {
207        self.check_needle_dtype(needle.dtype())?;
208        let needles = ConstantArray::new(needle.clone(), 1).into_array();
209        let (bits, needle_validity) = self.element_set(ctx)?.haystack.contains(&needles, ctx)?;
210        self.result_from_bits(bits, needle_validity, needle.dtype(), options)?
211            .execute_scalar(0, ctx)
212    }
213
214    /// Makes the result of [`Self::contains`] from one membership bit per needle.
215    ///
216    /// A kernel that finds the matches of its needles without this haystack, for example from
217    /// bounds of its own, uses this to apply the null semantics of [`Self::contains`]. A set bit
218    /// in `bits` tells that the needle equals an element. `needle_validity` is the validity of the
219    /// needles, and `needle_dtype` is their dtype. The bit of a null needle has no effect.
220    ///
221    /// # Errors
222    ///
223    /// Fails when `needle_dtype` is not the dtype of the list's elements, or when
224    /// `needle_validity` does not have one row per bit.
225    pub fn result_from_bits(
226        &self,
227        bits: BitBuffer,
228        needle_validity: Validity,
229        needle_dtype: &DType,
230        options: &ListContainsOptions,
231    ) -> VortexResult<ArrayRef> {
232        self.check_needle_dtype(needle_dtype)?;
233        if let Some(len) = needle_validity.maybe_len() {
234            vortex_ensure!(
235                len == bits.len(),
236                "Needle validity has {len} rows, but there are {} membership bits",
237                bits.len()
238            );
239        }
240
241        options.result_from_bits(
242            bits,
243            needle_validity,
244            self.list_dtype(),
245            needle_dtype,
246            self.0.is_empty,
247            self.0.has_null_element,
248        )
249    }
250
251    /// Fails when needles of `needle_dtype` cannot be elements of the list.
252    fn check_needle_dtype(&self, needle_dtype: &DType) -> VortexResult<()> {
253        let element_dtype = self.element_dtype();
254        if !element_dtype.eq_ignore_nullability(needle_dtype) {
255            vortex_bail!(
256                "Element type {} of list does not match search value {}",
257                element_dtype,
258                needle_dtype,
259            );
260        }
261        Ok(())
262    }
263}
264
265impl Debug for PreparedSetData {
266    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
267        f.debug_struct("PreparedSetData")
268            .field("list", self.list())
269            .finish_non_exhaustive()
270    }
271}
272
273impl Display for PreparedSetData {
274    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
275        write!(f, "{}", self.list())
276    }
277}
278
279impl PartialEq for PreparedSetData {
280    fn eq(&self, other: &Self) -> bool {
281        self.list() == other.list()
282    }
283}
284
285impl Eq for PreparedSetData {}
286
287impl Hash for PreparedSetData {
288    fn hash<H: Hasher>(&self, state: &mut H) {
289        self.list().hash(state);
290    }
291}