Skip to main content

vortex_layout/layouts/list/
writer.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::sync::Arc;
5
6use async_trait::async_trait;
7use futures::StreamExt;
8use futures::future::try_join;
9use futures::future::try_join_all;
10use vortex_array::ArrayRef;
11use vortex_array::ExecutionCtx;
12use vortex_array::IntoArray;
13use vortex_array::VortexSessionExecute;
14use vortex_array::arrays::ConstantArray;
15use vortex_array::arrays::List;
16use vortex_array::arrays::ListView;
17use vortex_array::arrays::PrimitiveArray;
18use vortex_array::arrays::list::ListDataParts;
19use vortex_array::arrays::listview::list_from_list_view;
20use vortex_array::builtins::ArrayBuiltins;
21use vortex_array::dtype::DType;
22use vortex_array::dtype::Nullability;
23use vortex_array::dtype::PType;
24use vortex_array::matcher::Matcher;
25use vortex_array::scalar_fn::fns::operators::Operator;
26use vortex_error::VortexExpect;
27use vortex_error::VortexResult;
28use vortex_error::vortex_bail;
29use vortex_io::kanal_ext::KanalExt;
30use vortex_io::session::RuntimeSessionExt;
31use vortex_session::VortexSession;
32
33use crate::LayoutRef;
34use crate::LayoutStrategy;
35use crate::LayoutWriterContext;
36use crate::layouts::flat::writer::FlatLayoutStrategy;
37use crate::layouts::list::ListLayout;
38use crate::segments::SegmentSinkRef;
39use crate::sequence::SendableSequentialStream;
40use crate::sequence::SequenceId;
41use crate::sequence::SequencePointer;
42use crate::sequence::SequentialStream;
43use crate::sequence::SequentialStreamAdapter;
44use crate::sequence::SequentialStreamExt;
45
46/// Item carried on each child sub-stream: a sequenced, materialized chunk.
47type ChildChunk = VortexResult<(SequenceId, ArrayRef)>;
48
49/// Strategy for writing list-typed arrays, with a fallback for non-list dtypes.
50///
51/// This is a *structural* writer that decomposes a list column into independent `elements`,
52/// `offsets`, and (when nullable) `validity` sub-columns, each written through its own downstream
53/// strategy, producing a single [`ListLayout`].
54///
55/// For list-typed input the strategy transposes the whole column stream into three sub-streams:
56///  1. Each chunk is canonicalized to a [`ListArray`] (rebuilding a [`ListView`] via
57///     [`list_from_list_view`] when necessary).
58///  2. `offsets` are rebased to global `u64` positions (cumulative across chunks) so the single
59///     `offsets` child indexes into the concatenated `elements` child.
60///  3. `elements`, `offsets`, and `validity` are streamed to their child strategies concurrently.
61///
62/// For input whose dtype is not [`DType::List`], the stream is forwarded unchanged to the
63/// configured `fallback` strategy.
64///
65/// [`ListArray`]: vortex_array::arrays::ListArray
66#[derive(Clone)]
67pub struct ListLayoutStrategy {
68    elements: Arc<dyn LayoutStrategy>,
69    offsets: Arc<dyn LayoutStrategy>,
70    validity: Arc<dyn LayoutStrategy>,
71    fallback: Arc<dyn LayoutStrategy>,
72}
73
74impl Default for ListLayoutStrategy {
75    /// Routes every child (elements, offsets, validity) and the non-list fallback through
76    /// [`FlatLayoutStrategy`]. Override individual children with the `with_*` builder methods.
77    fn default() -> Self {
78        let flat: Arc<dyn LayoutStrategy> = Arc::new(FlatLayoutStrategy::default());
79        Self {
80            elements: Arc::clone(&flat),
81            offsets: Arc::clone(&flat),
82            validity: Arc::clone(&flat),
83            fallback: flat,
84        }
85    }
86}
87
88impl ListLayoutStrategy {
89    /// Strategy for the `elements` child.
90    pub fn with_elements(mut self, elements: Arc<dyn LayoutStrategy>) -> Self {
91        self.elements = elements;
92        self
93    }
94
95    /// Strategy for the `offsets` child.
96    pub fn with_offsets(mut self, offsets: Arc<dyn LayoutStrategy>) -> Self {
97        self.offsets = offsets;
98        self
99    }
100
101    /// Strategy for the `validity` child (written only when the list is nullable).
102    pub fn with_validity(mut self, validity: Arc<dyn LayoutStrategy>) -> Self {
103        self.validity = validity;
104        self
105    }
106
107    /// Strategy for non-list input, which is forwarded through this strategy unchanged.
108    pub fn with_fallback(mut self, fallback: Arc<dyn LayoutStrategy>) -> Self {
109        self.fallback = fallback;
110        self
111    }
112}
113
114#[async_trait]
115impl LayoutStrategy for ListLayoutStrategy {
116    async fn write_stream(
117        &self,
118        ctx: LayoutWriterContext,
119        segment_sink: SegmentSinkRef,
120        stream: SendableSequentialStream,
121        mut eof: SequencePointer,
122        session: &VortexSession,
123    ) -> VortexResult<LayoutRef> {
124        let dtype = stream.dtype().clone();
125        if !dtype.is_list() {
126            return self
127                .fallback
128                .write_stream(ctx, segment_sink, stream, eof, session)
129                .await;
130        }
131
132        let is_nullable = dtype.is_nullable();
133        let element_dtype = dtype
134            .as_list_element_opt()
135            .vortex_expect("DType is List")
136            .as_ref()
137            .clone();
138        // Global (whole-column) offsets are cumulative and may exceed the input offset width,
139        // so definsively widen.
140        let offsets_dtype = DType::Primitive(PType::U64, Nullability::NonNullable);
141
142        // One bounded sub-stream per child: elements, offsets, and (when nullable) validity.
143        let (elements_tx, elements_rx) = kanal::bounded_async::<ChildChunk>(1);
144        let (offsets_tx, offsets_rx) = kanal::bounded_async::<ChildChunk>(1);
145        let (validity_tx, validity_rx) = if is_nullable {
146            let (tx, rx) = kanal::bounded_async::<ChildChunk>(1);
147            (Some(tx), Some(rx))
148        } else {
149            (None, None)
150        };
151
152        // Transpose the list column into its child sub-streams and rebase offsets to global
153        // positions. Kept joined with the child writers below so producer errors surface rather
154        // than being hidden as an early channel close.
155        let fanout_fut = transpose_list_column(
156            stream,
157            session.clone(),
158            elements_tx,
159            offsets_tx,
160            validity_tx,
161        );
162
163        // Spawn a writer per child sub-stream, concurrently.
164        let handle = session.handle();
165        let mut child_specs: Vec<(
166            DType,
167            Arc<dyn LayoutStrategy>,
168            kanal::AsyncReceiver<ChildChunk>,
169        )> = vec![
170            (element_dtype, Arc::clone(&self.elements), elements_rx),
171            (offsets_dtype, Arc::clone(&self.offsets), offsets_rx),
172        ];
173        if let Some(validity_rx) = validity_rx {
174            child_specs.push((
175                DType::Bool(Nullability::NonNullable),
176                Arc::clone(&self.validity),
177                validity_rx,
178            ));
179        }
180
181        let layout_futures: Vec<_> = child_specs
182            .into_iter()
183            .map(|(child_dtype, strategy, rx)| {
184                let child_stream =
185                    SequentialStreamAdapter::new(child_dtype, rx.into_stream().boxed()).sendable();
186                let child_eof = eof.split_off();
187                let ctx = ctx.clone();
188                let segment_sink = Arc::clone(&segment_sink);
189                let session = session.clone();
190                handle.spawn_nested(move |h| async move {
191                    let session = session.with_handle(h);
192                    strategy
193                        .write_stream(ctx, segment_sink, child_stream, child_eof, &session)
194                        .await
195                })
196            })
197            .collect();
198
199        let (_, layouts) = try_join(fanout_fut, try_join_all(layout_futures)).await?;
200        let mut layouts = layouts.into_iter();
201        let elements_layout = layouts.next().vortex_expect("elements layout present");
202        let offsets_layout = layouts.next().vortex_expect("offsets layout present");
203        let validity_layout =
204            is_nullable.then(|| layouts.next().vortex_expect("validity layout present"));
205
206        Ok(ListLayout::new(dtype, elements_layout, offsets_layout, validity_layout).into_layout())
207    }
208}
209
210/// Transpose a list column into its `elements`, `offsets`, and (when present) `validity` child
211/// sub-streams, rebasing each chunk's local `offsets` to global `u64` positions so the single
212/// `offsets` child indexes into the concatenated `elements` child.
213///
214/// `validity_tx` is `Some` exactly when the list is nullable. Errors surface to the caller, which
215/// joins this against the child writers, rather than being hidden as an early channel close.
216async fn transpose_list_column(
217    mut stream: SendableSequentialStream,
218    session: VortexSession,
219    elements_tx: kanal::AsyncSender<ChildChunk>,
220    offsets_tx: kanal::AsyncSender<ChildChunk>,
221    validity_tx: Option<kanal::AsyncSender<ChildChunk>>,
222) -> VortexResult<()> {
223    let mut exec_ctx = session.create_execution_ctx();
224    let mut element_base: u64 = 0;
225    let mut first = true;
226    let mut saw_chunk = false;
227    while let Some(chunk) = stream.next().await {
228        let (sequence_id, array) = chunk?;
229        saw_chunk = true;
230        let mut sp = sequence_id.descend();
231        let ListDataParts {
232            elements,
233            offsets,
234            validity,
235            ..
236        } = canonicalize_to_list_parts(array, &mut exec_ctx)?;
237        let n_elements = elements.len() as u64;
238        let row_count = offsets.len().saturating_sub(1);
239        let offsets = global_offsets(offsets, element_base, first, &mut exec_ctx)?;
240        element_base += n_elements;
241        first = false;
242
243        if elements_tx
244            .send(Ok((sp.advance(), elements)))
245            .await
246            .is_err()
247            || offsets_tx.send(Ok((sp.advance(), offsets))).await.is_err()
248        {
249            vortex_bail!("list child writer finished before all chunks were sent");
250        }
251        if let Some(validity_tx) = &validity_tx {
252            let validity = validity
253                .execute_mask(row_count, &mut exec_ctx)?
254                .into_array();
255            if validity_tx
256                .send(Ok((sp.advance(), validity)))
257                .await
258                .is_err()
259            {
260                vortex_bail!("list validity writer finished before all chunks were sent");
261            }
262        }
263    }
264    if !saw_chunk {
265        vortex_bail!("ListLayoutStrategy needs at least one chunk");
266    }
267    Ok(())
268}
269
270/// Canonicalize a list-dtype array into [`ListDataParts`].
271fn canonicalize_to_list_parts(
272    array: ArrayRef,
273    exec_ctx: &mut ExecutionCtx,
274) -> VortexResult<ListDataParts> {
275    let canonical = array.execute_until::<AnyList>(exec_ctx)?;
276    if let Some(list) = canonical.as_opt::<List>() {
277        Ok(list.into_owned().into_data_parts())
278    } else if let Some(view) = canonical.as_opt::<ListView>() {
279        Ok(list_from_list_view(view.into_owned(), exec_ctx)?.into_data_parts())
280    } else {
281        unreachable!("AnyList matcher guarantees List or ListView")
282    }
283}
284
285/// Rebase a chunk's local `offsets` into global `u64` positions for the whole-column `offsets`
286/// child. Each chunk's offsets are shifted by `element_base` (the number of elements already
287/// emitted) so they index into the concatenated `elements`. The duplicated boundary offset is
288/// dropped on every chunk after the first, so the concatenation of all chunks' contributions is a
289/// single monotonic `[0, .., total_elements]` array of length `row_count + 1`.
290fn global_offsets(
291    offsets: ArrayRef,
292    element_base: u64,
293    first: bool,
294    exec_ctx: &mut ExecutionCtx,
295) -> VortexResult<ArrayRef> {
296    let widened = offsets.cast(DType::Primitive(PType::U64, Nullability::NonNullable))?;
297    let based = if element_base == 0 {
298        widened
299    } else {
300        let base = ConstantArray::new(element_base, widened.len()).into_array();
301        widened.binary(base, Operator::Add)?
302    };
303    let based = if first {
304        based
305    } else {
306        based.slice(1..based.len())?
307    };
308    // Materialize so the child sub-stream carries a concrete array rather than a lazy expression.
309    Ok(based.execute::<PrimitiveArray>(exec_ctx)?.into_array())
310}
311
312/// Matcher for `Array<List>` or `Array<ListView>`.
313struct AnyList;
314
315impl Matcher for AnyList {
316    type Match<'a> = ();
317
318    fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
319        (array.as_opt::<List>().is_some() || array.as_opt::<ListView>().is_some()).then_some(())
320    }
321}
322
323#[cfg(test)]
324mod tests {
325    use futures::stream;
326    use vortex_array::ArrayContext;
327    use vortex_array::arrays::BoolArray;
328    use vortex_array::arrays::ChunkedArray;
329    use vortex_array::arrays::ListArray;
330    use vortex_array::arrays::StructArray;
331    use vortex_array::dtype::Nullability;
332    use vortex_array::dtype::PType;
333    use vortex_array::validity::Validity;
334    use vortex_buffer::buffer;
335    use vortex_io::session::RuntimeSession;
336
337    use super::*;
338    use crate::layouts::chunked::writer::ChunkedLayoutStrategy;
339    use crate::layouts::flat::writer::FlatLayoutStrategy;
340    use crate::layouts::table::TableStrategy;
341    use crate::segments::TestSegments;
342    use crate::sequence::SequentialArrayStreamExt;
343    use crate::session::LayoutSession;
344
345    fn layout_test_session() -> VortexSession {
346        vortex_array::array_session()
347            .with::<LayoutSession>()
348            .with::<RuntimeSession>()
349            .with_tokio()
350    }
351
352    fn flat_list_strategy() -> ListLayoutStrategy {
353        ListLayoutStrategy::default()
354    }
355
356    async fn write<S: LayoutStrategy>(strategy: &S, array: ArrayRef) -> VortexResult<LayoutRef> {
357        let session = layout_test_session();
358        let segments = Arc::new(TestSegments::default());
359        let (ptr, eof) = SequenceId::root().split();
360        let stream = array.to_array_stream().sequenced(ptr);
361        strategy
362            .write_stream(
363                ArrayContext::empty().into(),
364                segments,
365                stream,
366                eof,
367                &session,
368            )
369            .await
370    }
371
372    fn i32_list_dtype(nullable: bool) -> DType {
373        DType::List(
374            Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)),
375            if nullable {
376                Nullability::Nullable
377            } else {
378                Nullability::NonNullable
379            },
380        )
381    }
382
383    fn create_basic_list(validity: Validity) -> ArrayRef {
384        ListArray::try_new(
385            buffer![1i32, 2, 3, 4, 5].into_array(),
386            buffer![0u32, 2, 5, 5].into_array(),
387            validity,
388        )
389        .unwrap()
390        .into_array()
391    }
392
393    #[tokio::test]
394    async fn basic_non_nullable_input() -> VortexResult<()> {
395        let list = create_basic_list(Validity::NonNullable);
396
397        let layout = write(&flat_list_strategy(), list).await?;
398        assert_eq!(layout.row_count(), 3);
399
400        insta::assert_snapshot!(layout.display_tree(), @"
401        vortex.list, dtype: list(i32), children: 2
402        ├── elements: vortex.flat, dtype: i32, segment: 0
403        └── offsets: vortex.flat, dtype: u64, segment: 1
404        ");
405        Ok(())
406    }
407
408    #[tokio::test]
409    async fn basic_nullable_input() -> VortexResult<()> {
410        let list = create_basic_list(Validity::Array(
411            BoolArray::from_iter([true, false, true]).into_array(),
412        ));
413
414        let layout = write(&flat_list_strategy(), list).await?;
415        assert_eq!(layout.row_count(), 3);
416
417        insta::assert_snapshot!(layout.display_tree(), @"
418        vortex.list, dtype: list(i32)?, children: 3
419        ├── elements: vortex.flat, dtype: i32, segment: 0
420        ├── offsets: vortex.flat, dtype: u64, segment: 1
421        └── validity: vortex.flat, dtype: bool, segment: 2
422        ");
423        Ok(())
424    }
425
426    /// Non-list input dispatches to the fallback strategy unchanged.
427    #[tokio::test]
428    async fn non_list_input_routes_to_fallback() -> VortexResult<()> {
429        let primitive = buffer![1i32, 2, 3].into_array();
430        let layout = write(&flat_list_strategy(), primitive).await?;
431        insta::assert_snapshot!(layout.display_tree(), @"vortex.flat, dtype: i32, segment: 0");
432        Ok(())
433    }
434
435    #[tokio::test]
436    async fn empty_stream_errors() {
437        let segments = Arc::new(TestSegments::default());
438        let (_, eof) = SequenceId::root().split();
439        let empty = stream::empty::<VortexResult<(SequenceId, ArrayRef)>>().boxed();
440        let stream = SequentialStreamAdapter::new(i32_list_dtype(false), empty).sendable();
441        let session = layout_test_session();
442
443        let res = flat_list_strategy()
444            .write_stream(
445                ArrayContext::empty().into(),
446                segments,
447                stream,
448                eof,
449                &session,
450            )
451            .await;
452        assert!(res.is_err())
453    }
454
455    #[tokio::test]
456    async fn list_of_struct_tree() -> VortexResult<()> {
457        let struct_array = StructArray::from_fields(
458            [
459                ("a", buffer![1i32, 2, 3, 4, 5].into_array()),
460                ("b", buffer![10i32, 20, 30, 40, 50].into_array()),
461            ]
462            .as_slice(),
463        )?
464        .into_array();
465        let list = ListArray::try_new(
466            struct_array,
467            buffer![0u32, 2, 5, 5].into_array(),
468            Validity::NonNullable,
469        )?
470        .into_array();
471
472        let flat: Arc<dyn LayoutStrategy> = Arc::new(FlatLayoutStrategy::default());
473        let table_strategy: Arc<dyn LayoutStrategy> =
474            Arc::new(TableStrategy::new(Arc::clone(&flat), Arc::clone(&flat)));
475        let writer = ListLayoutStrategy::default().with_elements(table_strategy);
476
477        let layout = write(&writer, list).await?;
478        insta::assert_snapshot!(layout.display_tree(), @"
479        vortex.list, dtype: list({a=i32, b=i32}), children: 2
480        ├── elements: vortex.struct, dtype: {a=i32, b=i32}, children: 2
481        │   ├── a: vortex.flat, dtype: i32, segment: 1
482        │   └── b: vortex.flat, dtype: i32, segment: 2
483        └── offsets: vortex.flat, dtype: u64, segment: 0
484        ");
485        Ok(())
486    }
487
488    #[tokio::test]
489    async fn list_of_list_tree() -> VortexResult<()> {
490        let inner_list = ListArray::try_new(
491            buffer![1i32, 2, 3, 4, 5, 6].into_array(),
492            buffer![0u32, 2, 5, 5, 6].into_array(),
493            Validity::NonNullable,
494        )?
495        .into_array();
496        let list = ListArray::try_new(
497            inner_list,
498            buffer![0u32, 2, 4].into_array(),
499            Validity::NonNullable,
500        )?
501        .into_array();
502
503        let writer =
504            ListLayoutStrategy::default().with_elements(Arc::new(ListLayoutStrategy::default()));
505        let layout = write(&writer, list).await?;
506        insta::assert_snapshot!(layout.display_tree(), @"
507        vortex.list, dtype: list(list(i32)), children: 2
508        ├── elements: vortex.list, dtype: list(i32), children: 2
509        │   ├── elements: vortex.flat, dtype: i32, segment: 1
510        │   └── offsets: vortex.flat, dtype: u64, segment: 2
511        └── offsets: vortex.flat, dtype: u64, segment: 0
512        ");
513        Ok(())
514    }
515
516    #[tokio::test]
517    async fn list_of_list_of_list_tree() -> VortexResult<()> {
518        let innermost = ListArray::try_new(
519            buffer![1i32, 2, 3, 4].into_array(),
520            buffer![0u32, 2, 4].into_array(),
521            Validity::NonNullable,
522        )?
523        .into_array();
524        let middle = ListArray::try_new(
525            innermost,
526            buffer![0u32, 2].into_array(),
527            Validity::NonNullable,
528        )?
529        .into_array();
530        let outer =
531            ListArray::try_new(middle, buffer![0u32, 1].into_array(), Validity::NonNullable)?
532                .into_array();
533
534        let writer = ListLayoutStrategy::default().with_elements(Arc::new(
535            ListLayoutStrategy::default().with_elements(Arc::new(ListLayoutStrategy::default())),
536        ));
537        let layout = write(&writer, outer).await?;
538        insta::assert_snapshot!(layout.display_tree(), @"
539        vortex.list, dtype: list(list(list(i32))), children: 2
540        ├── elements: vortex.list, dtype: list(list(i32)), children: 2
541        │   ├── elements: vortex.list, dtype: list(i32), children: 2
542        │   │   ├── elements: vortex.flat, dtype: i32, segment: 2
543        │   │   └── offsets: vortex.flat, dtype: u64, segment: 3
544        │   └── offsets: vortex.flat, dtype: u64, segment: 1
545        └── offsets: vortex.flat, dtype: u64, segment: 0
546        ");
547        Ok(())
548    }
549
550    #[tokio::test]
551    async fn chunked_list_input_with_chunked_strategy_succeeds() -> VortexResult<()> {
552        let chunk0 = ListArray::try_new(
553            buffer![1i32, 2, 3].into_array(),
554            buffer![0u32, 2, 3].into_array(),
555            Validity::NonNullable,
556        )
557        .unwrap()
558        .into_array();
559        let chunk1 = ListArray::try_new(
560            buffer![4i32, 5, 6, 7].into_array(),
561            buffer![0u32, 1, 4].into_array(),
562            Validity::NonNullable,
563        )
564        .unwrap()
565        .into_array();
566
567        let chunked =
568            ChunkedArray::try_new(vec![chunk0, chunk1], i32_list_dtype(false))?.into_array();
569
570        let layout = write(&ChunkedLayoutStrategy::new(flat_list_strategy()), chunked).await?;
571
572        insta::assert_snapshot!(layout.display_tree(), @"
573        vortex.chunked, dtype: list(i32), children: 2
574        ├── [0]: vortex.list, dtype: list(i32), children: 2
575        │   ├── elements: vortex.flat, dtype: i32, segment: 0
576        │   └── offsets: vortex.flat, dtype: u64, segment: 1
577        └── [1]: vortex.list, dtype: list(i32), children: 2
578            ├── elements: vortex.flat, dtype: i32, segment: 2
579            └── offsets: vortex.flat, dtype: u64, segment: 3
580        ");
581        Ok(())
582    }
583}