Skip to main content

vortex_array/builders/
variant.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::any::Any;
5
6use vortex_error::VortexExpect;
7use vortex_error::VortexResult;
8use vortex_error::vortex_bail;
9use vortex_error::vortex_ensure;
10
11use crate::ArrayRef;
12use crate::ExecutionCtx;
13use crate::IntoArray;
14use crate::arrays::ChunkedArray;
15use crate::arrays::ConstantArray;
16use crate::arrays::VariantArray;
17use crate::arrays::variant::VariantArraySlotsExt;
18use crate::builders::ArrayBuilder;
19use crate::builtins::ArrayBuiltins;
20use crate::canonical::Canonical;
21use crate::dtype::DType;
22use crate::dtype::Nullability;
23use crate::scalar::Scalar;
24
25/// Builds the core storage of a Variant in the physical encoding of one storage array.
26///
27/// A [`VariantBuilder`] cannot merge the storage it receives, because the canonical Variant
28/// leaves the storage encoding open. A storage encoding that can merge its arrays installs a
29/// builder of its own through [`VariantBuilder::append_storage`] instead, so that consecutive
30/// arrays of that encoding finish as one array of it rather than one chunk each.
31pub trait VariantStorageBuilder: Send + 'static {
32    /// Returns the builder as [`Any`], so that its encoding can recognise it.
33    fn as_any_mut(&mut self) -> &mut dyn Any;
34
35    /// The number of rows appended so far.
36    fn len(&self) -> usize;
37
38    /// Whether no row has been appended.
39    fn is_empty(&self) -> bool {
40        self.len() == 0
41    }
42
43    /// Finishes the storage, an array of the builder's Variant dtype with one row per appended row.
44    fn finish(self: Box<Self>) -> VortexResult<ArrayRef>;
45}
46
47/// A part of the core storage, in row order.
48enum CorePart {
49    /// Storage kept in the encoding it was appended in.
50    Chunk(ArrayRef),
51    /// Storage merged by the builder of its encoding.
52    Storage(Box<dyn VariantStorageBuilder>),
53    /// A run of one scalar.
54    Run(Scalar, usize),
55}
56
57impl CorePart {
58    fn len(&self) -> usize {
59        match self {
60            CorePart::Chunk(chunk) => chunk.len(),
61            CorePart::Storage(storage) => storage.len(),
62            CorePart::Run(_, len) => *len,
63        }
64    }
65
66    fn finish(self) -> VortexResult<ArrayRef> {
67        match self {
68            CorePart::Chunk(chunk) => Ok(chunk),
69            CorePart::Storage(storage) => storage.finish(),
70            CorePart::Run(scalar, len) => Ok(ConstantArray::new(scalar, len).into_array()),
71        }
72    }
73}
74
75/// A part of the shredded child, in row order.
76enum ShreddedPart {
77    /// Shredded values of the rows of a Variant that had a shredded child.
78    Array(ArrayRef),
79    /// Rows of Variants without a shredded child, whose values are all in the core storage.
80    Unshredded(usize),
81}
82
83/// The builder for building a [`VariantArray`].
84///
85/// The core storage of the result keeps the encodings it was appended in. Consecutive storage
86/// arrays of an encoding that installs a [`VariantStorageBuilder`] merge into one array of that
87/// encoding; any other storage, and runs of scalars, become chunks of their own.
88///
89/// The shredded children of the appended Variants are concatenated. Rows from Variants without a
90/// shredded child are null in it, which marks their values as held by the core storage alone; the
91/// shredded child is then nullable even if the appended ones are not. Every shredded child must
92/// have the same dtype, up to nullability.
93pub struct VariantBuilder {
94    dtype: DType,
95    /// The core storage, in row order. Only the last part grows.
96    core: Vec<CorePart>,
97    /// The number of rows in every part of `core` but the last.
98    finished_len: usize,
99    shredded: Vec<ShreddedPart>,
100    /// The number of rows `shredded` covers.
101    shredded_len: usize,
102    /// Whether the builder is appending the core storage of a canonical Variant.
103    in_core: bool,
104}
105
106impl VariantBuilder {
107    /// Creates a builder for Variants of `nullability`.
108    pub fn new(nullability: Nullability) -> Self {
109        Self {
110            dtype: DType::Variant(nullability),
111            core: Vec::new(),
112            finished_len: 0,
113            shredded: Vec::new(),
114            shredded_len: 0,
115            in_core: false,
116        }
117    }
118
119    /// Appends the rows of a canonical Variant.
120    ///
121    /// The core storage is appended through its encoding, which may merge it into the storage
122    /// appended before it.
123    pub fn append_variant_array(
124        &mut self,
125        array: &VariantArray,
126        ctx: &mut ExecutionCtx,
127    ) -> VortexResult<()> {
128        self.check_dtype(array.dtype())?;
129        if array.is_empty() {
130            return Ok(());
131        }
132        if self.in_core {
133            // A storage encoding without a storage builder of its own executes to a canonical
134            // Variant over itself, and its rows are kept as they are. So are those of a core
135            // storage that holds shredded values of its own.
136            let chunk = if array.shredded().is_some() {
137                array.clone().into_array()
138            } else {
139                array.core_storage().clone()
140            };
141            self.push(CorePart::Chunk(chunk));
142            return Ok(());
143        }
144
145        if let Some(shredded) = array.shredded() {
146            if let Some(ShreddedPart::Array(first)) = self
147                .shredded
148                .iter()
149                .find(|part| matches!(part, ShreddedPart::Array(_)))
150            {
151                vortex_ensure!(
152                    first.dtype().eq_ignore_nullability(shredded.dtype()),
153                    "cannot build a Variant from Variants shredded as {} and as {}",
154                    first.dtype(),
155                    shredded.dtype()
156                );
157            }
158            self.pad_shredded(self.len());
159            self.shredded_len += shredded.len();
160            self.shredded.push(ShreddedPart::Array(shredded.clone()));
161        }
162        self.in_core = true;
163        let appended = array.core_storage().append_to_builder(self, ctx);
164        self.in_core = false;
165        appended
166    }
167
168    /// Appends rows of core storage through the [`VariantStorageBuilder`] of type `B`.
169    ///
170    /// If the storage appended last went through a builder of type `B`, `append` extends it.
171    /// Otherwise `new` creates one for the builder's dtype.
172    pub fn append_storage<B: VariantStorageBuilder>(
173        &mut self,
174        dtype: &DType,
175        new: impl FnOnce(&DType) -> B,
176        append: impl FnOnce(&mut B) -> VortexResult<()>,
177    ) -> VortexResult<()> {
178        self.check_dtype(dtype)?;
179        let reuse = match self.core.last_mut() {
180            Some(CorePart::Storage(storage)) => storage.as_any_mut().is::<B>(),
181            _ => false,
182        };
183        if !reuse {
184            self.push(CorePart::Storage(Box::new(new(&self.dtype))));
185        }
186        let Some(CorePart::Storage(storage)) = self.core.last_mut() else {
187            vortex_bail!("the Variant storage builder was just installed");
188        };
189        let Some(storage) = storage.as_any_mut().downcast_mut::<B>() else {
190            vortex_bail!("the Variant storage builder has the type it was installed as");
191        };
192        append(storage)
193    }
194
195    /// Appends `n` copies of the Variant `scalar`.
196    pub fn append_n_scalars(&mut self, scalar: &Scalar, n: usize) -> VortexResult<()> {
197        self.check_dtype(scalar.dtype())?;
198        if n == 0 {
199            return Ok(());
200        }
201        let scalar = if scalar.dtype() == &self.dtype {
202            scalar.clone()
203        } else {
204            scalar.cast(&self.dtype)?
205        };
206        if let Some(CorePart::Run(run, len)) = self.core.last_mut()
207            && *run == scalar
208        {
209            *len += n;
210            return Ok(());
211        }
212        self.push(CorePart::Run(scalar, n));
213        Ok(())
214    }
215
216    /// Finishes the builder into a [`VariantArray`].
217    pub fn finish_into_variant(&mut self) -> VortexResult<VariantArray> {
218        let len = self.len();
219        let shredded = self.finish_shredded(len)?;
220        let mut chunks = std::mem::take(&mut self.core)
221            .into_iter()
222            .map(CorePart::finish)
223            .collect::<VortexResult<Vec<_>>>()?;
224        self.finished_len = 0;
225        let core = match chunks.len() {
226            1 => chunks.remove(0),
227            // An empty Variant is an empty chunked array: there is no empty canonical storage.
228            _ => ChunkedArray::try_new(chunks, self.dtype.clone())?.into_array(),
229        };
230        VariantArray::try_new(core, shredded)
231    }
232
233    /// Variants of the builder's nullability, and non-nullable Variants for a nullable builder,
234    /// can be appended.
235    fn check_dtype(&self, dtype: &DType) -> VortexResult<()> {
236        vortex_ensure!(
237            dtype.is_variant() && (self.dtype.is_nullable() || !dtype.is_nullable()),
238            "cannot append {dtype} to a builder of {}",
239            self.dtype
240        );
241        Ok(())
242    }
243
244    fn push(&mut self, part: CorePart) {
245        if part.len() == 0 && !matches!(part, CorePart::Storage(_)) {
246            return;
247        }
248        self.finished_len += self.core.last().map_or(0, CorePart::len);
249        self.core.push(part);
250    }
251
252    /// Marks the rows up to `len` that have no shredded child.
253    fn pad_shredded(&mut self, len: usize) {
254        if len > self.shredded_len {
255            self.shredded
256                .push(ShreddedPart::Unshredded(len - self.shredded_len));
257            self.shredded_len = len;
258        }
259    }
260
261    fn finish_shredded(&mut self, len: usize) -> VortexResult<Option<ArrayRef>> {
262        let Some(dtype) = self.shredded.iter().find_map(|part| match part {
263            ShreddedPart::Array(array) => Some(array.dtype().clone()),
264            ShreddedPart::Unshredded(_) => None,
265        }) else {
266            self.shredded.clear();
267            self.shredded_len = 0;
268            return Ok(None);
269        };
270        self.pad_shredded(len);
271        let parts = std::mem::take(&mut self.shredded);
272        self.shredded_len = 0;
273
274        let nullable = parts.iter().any(|part| match part {
275            ShreddedPart::Array(array) => array.dtype().is_nullable(),
276            ShreddedPart::Unshredded(_) => true,
277        });
278        let dtype = if nullable { dtype.as_nullable() } else { dtype };
279        let mut chunks = parts
280            .into_iter()
281            .map(|part| match part {
282                ShreddedPart::Array(array) => {
283                    vortex_ensure!(
284                        array.dtype().eq_ignore_nullability(&dtype),
285                        "cannot build a Variant from Variants shredded as {dtype} and as {}",
286                        array.dtype()
287                    );
288                    if array.dtype() == &dtype {
289                        Ok(array)
290                    } else {
291                        array.cast(dtype.clone())
292                    }
293                }
294                ShreddedPart::Unshredded(len) => {
295                    Ok(ConstantArray::new(Scalar::null(dtype.clone()), len).into_array())
296                }
297            })
298            .collect::<VortexResult<Vec<_>>>()?;
299        if chunks.len() == 1 {
300            return Ok(chunks.pop());
301        }
302        Ok(Some(ChunkedArray::try_new(chunks, dtype)?.into_array()))
303    }
304}
305
306impl ArrayBuilder for VariantBuilder {
307    fn as_any(&self) -> &dyn Any {
308        self
309    }
310
311    fn as_any_mut(&mut self) -> &mut dyn Any {
312        self
313    }
314
315    fn dtype(&self) -> &DType {
316        &self.dtype
317    }
318
319    fn len(&self) -> usize {
320        self.finished_len + self.core.last().map_or(0, CorePart::len)
321    }
322
323    fn append_zeros(&mut self, n: usize) {
324        let zero = Scalar::zero_value(&self.dtype);
325        self.append_n_scalars(&zero, n)
326            .vortex_expect("the zero value of the builder's dtype can be appended");
327    }
328
329    unsafe fn append_nulls_unchecked(&mut self, n: usize) {
330        let null = Scalar::null(self.dtype.clone());
331        self.append_n_scalars(&null, n)
332            .vortex_expect("a null of the builder's dtype can be appended");
333    }
334
335    fn append_scalar(&mut self, scalar: &Scalar) -> VortexResult<()> {
336        self.append_n_scalars(scalar, 1)
337    }
338
339    fn reserve_exact(&mut self, _additional: usize) {}
340
341    fn reserve_chunks(&mut self, additional: usize) {
342        self.core.reserve(additional);
343        self.shredded.reserve(additional);
344    }
345
346    fn finish(&mut self) -> ArrayRef {
347        self.finish_into_variant()
348            .vortex_expect("the appended Variants finish into one")
349            .into_array()
350    }
351
352    fn finish_into_canonical(&mut self, _ctx: &mut ExecutionCtx) -> Canonical {
353        Canonical::Variant(
354            self.finish_into_variant()
355                .vortex_expect("the appended Variants finish into one"),
356        )
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use std::sync::LazyLock;
363
364    use vortex_error::VortexResult;
365    use vortex_error::vortex_err;
366    use vortex_session::VortexSession;
367
368    use super::*;
369    use crate::VortexSessionExecute;
370    use crate::arrays::Chunked;
371    use crate::arrays::Constant;
372    use crate::arrays::PrimitiveArray;
373    use crate::arrays::chunked::ChunkedArrayExt;
374    use crate::assert_arrays_eq;
375    use crate::builders::builder_with_capacity_in;
376    use crate::memory::BufferAllocatorRef;
377
378    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
379
380    fn variant(value: i32) -> Scalar {
381        Scalar::variant(Scalar::primitive(value, Nullability::NonNullable))
382    }
383
384    /// The `i32` each row holds, or `None` for a null row.
385    fn values(array: &VariantArray) -> VortexResult<Vec<Option<i32>>> {
386        let mut ctx = SESSION.create_execution_ctx();
387        (0..array.len())
388            .map(|idx| {
389                let scalar = array.execute_scalar(idx, &mut ctx)?;
390                Ok(scalar
391                    .as_variant()
392                    .value()
393                    .and_then(|value| value.as_primitive().as_::<i32>()))
394            })
395            .collect()
396    }
397
398    #[test]
399    fn dispatches_on_the_variant_dtype() {
400        let builder = builder_with_capacity_in(
401            &DType::Variant(Nullability::Nullable),
402            4,
403            BufferAllocatorRef::static_ref(),
404        );
405        assert!(builder.as_any().is::<VariantBuilder>());
406    }
407
408    /// Repeated scalars, nulls included, become one constant run each.
409    #[test]
410    fn appends_scalars_as_runs() -> VortexResult<()> {
411        let mut builder = VariantBuilder::new(Nullability::Nullable);
412        builder.append_scalar(&variant(1))?;
413        builder.append_scalar(&variant(1))?;
414        builder.append_nulls(2);
415        builder.append_scalar(&variant(2))?;
416
417        let array = builder.finish_into_variant()?;
418        assert_eq!(values(&array)?, [Some(1), Some(1), None, None, Some(2)]);
419        let core = array.core_storage().as_::<Chunked>();
420        assert_eq!(core.nchunks(), 3);
421        assert!(core.iter_chunks().all(|chunk| chunk.is::<Constant>()));
422        Ok(())
423    }
424
425    /// Rows appended without a shredded child are null in it, so their values come from the
426    /// core storage.
427    #[test]
428    fn pads_the_shredded_child() -> VortexResult<()> {
429        let mut ctx = SESSION.create_execution_ctx();
430        let shredded = VariantArray::try_new(
431            ConstantArray::new(variant(1), 2).into_array(),
432            Some(PrimitiveArray::from_iter([10i32, 20]).into_array()),
433        )?;
434        let mut builder = VariantBuilder::new(Nullability::NonNullable);
435        builder.append_scalar(&variant(3))?;
436        builder.append_variant_array(&shredded, &mut ctx)?;
437        builder.append_scalar(&variant(4))?;
438
439        let array = builder.finish_into_variant()?;
440        assert_eq!(values(&array)?, [Some(3), Some(10), Some(20), Some(4)]);
441        let shredded = array
442            .shredded()
443            .ok_or_else(|| vortex_err!("expected a shredded child"))?;
444        assert_arrays_eq!(
445            shredded,
446            PrimitiveArray::from_option_iter([None, Some(10i32), Some(20), None]),
447            &mut ctx
448        );
449        Ok(())
450    }
451
452    /// The shredded children of the appended Variants are concatenated.
453    #[test]
454    fn concatenates_the_shredded_children() -> VortexResult<()> {
455        let mut ctx = SESSION.create_execution_ctx();
456        let mut builder = VariantBuilder::new(Nullability::NonNullable);
457        for (values, shredded) in [(vec![1, 2], vec![10i32, 20]), (vec![3], vec![30])] {
458            let core = ChunkedArray::try_new(
459                values
460                    .into_iter()
461                    .map(|value| ConstantArray::new(variant(value), 1).into_array()),
462                DType::Variant(Nullability::NonNullable),
463            )?;
464            let array = VariantArray::try_new(
465                core.into_array(),
466                Some(PrimitiveArray::from_iter(shredded).into_array()),
467            )?;
468            builder.append_variant_array(&array, &mut ctx)?;
469        }
470
471        let array = builder.finish_into_variant()?;
472        assert_eq!(values(&array)?, [Some(10), Some(20), Some(30)]);
473        let shredded = array
474            .shredded()
475            .ok_or_else(|| vortex_err!("expected a shredded child"))?;
476        assert_arrays_eq!(
477            shredded,
478            PrimitiveArray::from_iter([10i32, 20, 30]),
479            &mut ctx
480        );
481        Ok(())
482    }
483
484    #[test]
485    fn rejects_shredded_children_of_different_dtypes() -> VortexResult<()> {
486        let mut ctx = SESSION.create_execution_ctx();
487        let shredded = |value: i32, typed: ArrayRef| {
488            VariantArray::try_new(
489                ConstantArray::new(variant(value), 1).into_array(),
490                Some(typed),
491            )
492        };
493        let mut builder = VariantBuilder::new(Nullability::NonNullable);
494        builder.append_variant_array(
495            &shredded(1, PrimitiveArray::from_iter([10i32]).into_array())?,
496            &mut ctx,
497        )?;
498
499        let err = builder
500            .append_variant_array(
501                &shredded(2, PrimitiveArray::from_iter([20i64]).into_array())?,
502                &mut ctx,
503            )
504            .and_then(|()| builder.finish_into_variant().map(|_| ()))
505            .unwrap_err();
506        assert!(
507            err.to_string()
508                .contains("cannot build a Variant from Variants shredded as")
509        );
510        Ok(())
511    }
512
513    #[test]
514    fn rejects_nullable_variants_in_a_non_nullable_builder() {
515        let mut builder = VariantBuilder::new(Nullability::NonNullable);
516        let null = Scalar::null(DType::Variant(Nullability::Nullable));
517        assert!(builder.append_scalar(&null).is_err());
518    }
519
520    #[test]
521    fn finishes_empty() -> VortexResult<()> {
522        let array = VariantBuilder::new(Nullability::Nullable).finish_into_variant()?;
523        assert!(array.is_empty());
524        assert!(array.shredded().is_none());
525        Ok(())
526    }
527}