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 |_| async move {
191                    strategy
192                        .write_stream(ctx, segment_sink, child_stream, child_eof, &session)
193                        .await
194                })
195            })
196            .collect();
197
198        let (_, layouts) = try_join(fanout_fut, try_join_all(layout_futures)).await?;
199        let mut layouts = layouts.into_iter();
200        let elements_layout = layouts.next().vortex_expect("elements layout present");
201        let offsets_layout = layouts.next().vortex_expect("offsets layout present");
202        let validity_layout =
203            is_nullable.then(|| layouts.next().vortex_expect("validity layout present"));
204
205        Ok(ListLayout::new(dtype, elements_layout, offsets_layout, validity_layout).into_layout())
206    }
207}
208
209/// Transpose a list column into its `elements`, `offsets`, and (when present) `validity` child
210/// sub-streams, rebasing each chunk's local `offsets` to global `u64` positions so the single
211/// `offsets` child indexes into the concatenated `elements` child.
212///
213/// `validity_tx` is `Some` exactly when the list is nullable. Errors surface to the caller, which
214/// joins this against the child writers, rather than being hidden as an early channel close.
215async fn transpose_list_column(
216    mut stream: SendableSequentialStream,
217    session: VortexSession,
218    elements_tx: kanal::AsyncSender<ChildChunk>,
219    offsets_tx: kanal::AsyncSender<ChildChunk>,
220    validity_tx: Option<kanal::AsyncSender<ChildChunk>>,
221) -> VortexResult<()> {
222    let mut exec_ctx = session.create_execution_ctx();
223    let mut element_base: u64 = 0;
224    let mut first = true;
225    let mut saw_chunk = false;
226    while let Some(chunk) = stream.next().await {
227        let (sequence_id, array) = chunk?;
228        saw_chunk = true;
229        let mut sp = sequence_id.descend();
230        let ListDataParts {
231            elements,
232            offsets,
233            validity,
234            ..
235        } = canonicalize_to_list_parts(array, &mut exec_ctx)?;
236        let n_elements = elements.len() as u64;
237        let row_count = offsets.len().saturating_sub(1);
238        let offsets = global_offsets(offsets, element_base, first, &mut exec_ctx)?;
239        element_base += n_elements;
240        first = false;
241
242        if elements_tx
243            .send(Ok((sp.advance(), elements)))
244            .await
245            .is_err()
246            || offsets_tx.send(Ok((sp.advance(), offsets))).await.is_err()
247        {
248            vortex_bail!("list child writer finished before all chunks were sent");
249        }
250        if let Some(validity_tx) = &validity_tx {
251            let validity = validity
252                .execute_mask(row_count, &mut exec_ctx)?
253                .into_array();
254            if validity_tx
255                .send(Ok((sp.advance(), validity)))
256                .await
257                .is_err()
258            {
259                vortex_bail!("list validity writer finished before all chunks were sent");
260            }
261        }
262    }
263    if !saw_chunk {
264        vortex_bail!("ListLayoutStrategy needs at least one chunk");
265    }
266    Ok(())
267}
268
269/// Canonicalize a list-dtype array into [`ListDataParts`].
270fn canonicalize_to_list_parts(
271    array: ArrayRef,
272    exec_ctx: &mut ExecutionCtx,
273) -> VortexResult<ListDataParts> {
274    let canonical = array.execute_until::<AnyList>(exec_ctx)?;
275    if let Some(list) = canonical.as_opt::<List>() {
276        Ok(list.into_owned().into_data_parts())
277    } else if let Some(view) = canonical.as_opt::<ListView>() {
278        Ok(list_from_list_view(view.into_owned(), exec_ctx)?.into_data_parts())
279    } else {
280        unreachable!("AnyList matcher guarantees List or ListView")
281    }
282}
283
284/// Rebase a chunk's local `offsets` into global `u64` positions for the whole-column `offsets`
285/// child. Each chunk's offsets are shifted by `element_base` (the number of elements already
286/// emitted) so they index into the concatenated `elements`. The duplicated boundary offset is
287/// dropped on every chunk after the first, so the concatenation of all chunks' contributions is a
288/// single monotonic `[0, .., total_elements]` array of length `row_count + 1`.
289fn global_offsets(
290    offsets: ArrayRef,
291    element_base: u64,
292    first: bool,
293    exec_ctx: &mut ExecutionCtx,
294) -> VortexResult<ArrayRef> {
295    let widened = offsets.cast(DType::Primitive(PType::U64, Nullability::NonNullable))?;
296    let based = if element_base == 0 {
297        widened
298    } else {
299        let base = ConstantArray::new(element_base, widened.len()).into_array();
300        widened.binary(base, Operator::Add)?
301    };
302    let based = if first {
303        based
304    } else {
305        based.slice(1..based.len())?
306    };
307    // Materialize so the child sub-stream carries a concrete array rather than a lazy expression.
308    Ok(based.execute::<PrimitiveArray>(exec_ctx)?.into_array())
309}
310
311/// Matcher for `Array<List>` or `Array<ListView>`.
312struct AnyList;
313
314impl Matcher for AnyList {
315    type Match<'a> = ();
316
317    fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
318        (array.as_opt::<List>().is_some() || array.as_opt::<ListView>().is_some()).then_some(())
319    }
320}
321
322#[cfg(test)]
323mod tests {
324    use futures::stream;
325    use vortex_array::ArrayContext;
326    use vortex_array::arrays::BoolArray;
327    use vortex_array::arrays::ChunkedArray;
328    use vortex_array::arrays::ListArray;
329    use vortex_array::arrays::StructArray;
330    use vortex_array::dtype::Nullability;
331    use vortex_array::dtype::PType;
332    use vortex_array::validity::Validity;
333    use vortex_buffer::buffer;
334    use vortex_io::session::RuntimeSession;
335
336    use super::*;
337    use crate::layouts::chunked::writer::ChunkedLayoutStrategy;
338    use crate::layouts::flat::writer::FlatLayoutStrategy;
339    use crate::layouts::table::TableStrategy;
340    use crate::segments::TestSegments;
341    use crate::sequence::SequentialArrayStreamExt;
342    use crate::session::LayoutSession;
343
344    fn layout_test_session() -> VortexSession {
345        vortex_array::array_session()
346            .with::<LayoutSession>()
347            .with::<RuntimeSession>()
348            .with_tokio()
349    }
350
351    fn flat_list_strategy() -> ListLayoutStrategy {
352        ListLayoutStrategy::default()
353    }
354
355    async fn write<S: LayoutStrategy>(strategy: &S, array: ArrayRef) -> VortexResult<LayoutRef> {
356        let session = layout_test_session();
357        let segments = Arc::new(TestSegments::default());
358        let (ptr, eof) = SequenceId::root().split();
359        let stream = array.to_array_stream().sequenced(ptr);
360        strategy
361            .write_stream(
362                ArrayContext::empty().into(),
363                segments,
364                stream,
365                eof,
366                &session,
367            )
368            .await
369    }
370
371    fn i32_list_dtype(nullable: bool) -> DType {
372        DType::List(
373            Arc::new(DType::Primitive(PType::I32, Nullability::NonNullable)),
374            if nullable {
375                Nullability::Nullable
376            } else {
377                Nullability::NonNullable
378            },
379        )
380    }
381
382    fn create_basic_list(validity: Validity) -> ArrayRef {
383        ListArray::try_new(
384            buffer![1i32, 2, 3, 4, 5].into_array(),
385            buffer![0u32, 2, 5, 5].into_array(),
386            validity,
387        )
388        .unwrap()
389        .into_array()
390    }
391
392    #[tokio::test]
393    async fn basic_non_nullable_input() -> VortexResult<()> {
394        let list = create_basic_list(Validity::NonNullable);
395
396        let layout = write(&flat_list_strategy(), list).await?;
397        assert_eq!(layout.row_count(), 3);
398
399        insta::assert_snapshot!(layout.display_tree(), @"
400        vortex.list, dtype: list(i32), children: 2
401        ├── elements: vortex.flat, dtype: i32, segment: 0
402        └── offsets: vortex.flat, dtype: u64, segment: 1
403        ");
404        Ok(())
405    }
406
407    #[tokio::test]
408    async fn basic_nullable_input() -> VortexResult<()> {
409        let list = create_basic_list(Validity::Array(
410            BoolArray::from_iter([true, false, true]).into_array(),
411        ));
412
413        let layout = write(&flat_list_strategy(), list).await?;
414        assert_eq!(layout.row_count(), 3);
415
416        insta::assert_snapshot!(layout.display_tree(), @"
417        vortex.list, dtype: list(i32)?, children: 3
418        ├── elements: vortex.flat, dtype: i32, segment: 0
419        ├── offsets: vortex.flat, dtype: u64, segment: 1
420        └── validity: vortex.flat, dtype: bool, segment: 2
421        ");
422        Ok(())
423    }
424
425    /// Non-list input dispatches to the fallback strategy unchanged.
426    #[tokio::test]
427    async fn non_list_input_routes_to_fallback() -> VortexResult<()> {
428        let primitive = buffer![1i32, 2, 3].into_array();
429        let layout = write(&flat_list_strategy(), primitive).await?;
430        insta::assert_snapshot!(layout.display_tree(), @"vortex.flat, dtype: i32, segment: 0");
431        Ok(())
432    }
433
434    #[tokio::test]
435    async fn empty_stream_errors() {
436        let segments = Arc::new(TestSegments::default());
437        let (_, eof) = SequenceId::root().split();
438        let empty = stream::empty::<VortexResult<(SequenceId, ArrayRef)>>().boxed();
439        let stream = SequentialStreamAdapter::new(i32_list_dtype(false), empty).sendable();
440        let session = layout_test_session();
441
442        let res = flat_list_strategy()
443            .write_stream(
444                ArrayContext::empty().into(),
445                segments,
446                stream,
447                eof,
448                &session,
449            )
450            .await;
451        assert!(res.is_err())
452    }
453
454    #[tokio::test]
455    async fn list_of_struct_tree() -> VortexResult<()> {
456        let struct_array = StructArray::from_fields(
457            [
458                ("a", buffer![1i32, 2, 3, 4, 5].into_array()),
459                ("b", buffer![10i32, 20, 30, 40, 50].into_array()),
460            ]
461            .as_slice(),
462        )?
463        .into_array();
464        let list = ListArray::try_new(
465            struct_array,
466            buffer![0u32, 2, 5, 5].into_array(),
467            Validity::NonNullable,
468        )?
469        .into_array();
470
471        let flat: Arc<dyn LayoutStrategy> = Arc::new(FlatLayoutStrategy::default());
472        let table_strategy: Arc<dyn LayoutStrategy> =
473            Arc::new(TableStrategy::new(Arc::clone(&flat), Arc::clone(&flat)));
474        let writer = ListLayoutStrategy::default().with_elements(table_strategy);
475
476        let layout = write(&writer, list).await?;
477        insta::assert_snapshot!(layout.display_tree(), @"
478        vortex.list, dtype: list({a=i32, b=i32}), children: 2
479        ├── elements: vortex.struct, dtype: {a=i32, b=i32}, children: 2
480        │   ├── a: vortex.flat, dtype: i32, segment: 1
481        │   └── b: vortex.flat, dtype: i32, segment: 2
482        └── offsets: vortex.flat, dtype: u64, segment: 0
483        ");
484        Ok(())
485    }
486
487    #[tokio::test]
488    async fn list_of_list_tree() -> VortexResult<()> {
489        let inner_list = ListArray::try_new(
490            buffer![1i32, 2, 3, 4, 5, 6].into_array(),
491            buffer![0u32, 2, 5, 5, 6].into_array(),
492            Validity::NonNullable,
493        )?
494        .into_array();
495        let list = ListArray::try_new(
496            inner_list,
497            buffer![0u32, 2, 4].into_array(),
498            Validity::NonNullable,
499        )?
500        .into_array();
501
502        let writer =
503            ListLayoutStrategy::default().with_elements(Arc::new(ListLayoutStrategy::default()));
504        let layout = write(&writer, list).await?;
505        insta::assert_snapshot!(layout.display_tree(), @"
506        vortex.list, dtype: list(list(i32)), children: 2
507        ├── elements: vortex.list, dtype: list(i32), children: 2
508        │   ├── elements: vortex.flat, dtype: i32, segment: 1
509        │   └── offsets: vortex.flat, dtype: u64, segment: 2
510        └── offsets: vortex.flat, dtype: u64, segment: 0
511        ");
512        Ok(())
513    }
514
515    #[tokio::test]
516    async fn list_of_list_of_list_tree() -> VortexResult<()> {
517        let innermost = ListArray::try_new(
518            buffer![1i32, 2, 3, 4].into_array(),
519            buffer![0u32, 2, 4].into_array(),
520            Validity::NonNullable,
521        )?
522        .into_array();
523        let middle = ListArray::try_new(
524            innermost,
525            buffer![0u32, 2].into_array(),
526            Validity::NonNullable,
527        )?
528        .into_array();
529        let outer =
530            ListArray::try_new(middle, buffer![0u32, 1].into_array(), Validity::NonNullable)?
531                .into_array();
532
533        let writer = ListLayoutStrategy::default().with_elements(Arc::new(
534            ListLayoutStrategy::default().with_elements(Arc::new(ListLayoutStrategy::default())),
535        ));
536        let layout = write(&writer, outer).await?;
537        insta::assert_snapshot!(layout.display_tree(), @"
538        vortex.list, dtype: list(list(list(i32))), children: 2
539        ├── elements: vortex.list, dtype: list(list(i32)), children: 2
540        │   ├── elements: vortex.list, dtype: list(i32), children: 2
541        │   │   ├── elements: vortex.flat, dtype: i32, segment: 2
542        │   │   └── offsets: vortex.flat, dtype: u64, segment: 3
543        │   └── offsets: vortex.flat, dtype: u64, segment: 1
544        └── offsets: vortex.flat, dtype: u64, segment: 0
545        ");
546        Ok(())
547    }
548
549    #[tokio::test]
550    async fn chunked_list_input_with_chunked_strategy_succeeds() -> VortexResult<()> {
551        let chunk0 = ListArray::try_new(
552            buffer![1i32, 2, 3].into_array(),
553            buffer![0u32, 2, 3].into_array(),
554            Validity::NonNullable,
555        )
556        .unwrap()
557        .into_array();
558        let chunk1 = ListArray::try_new(
559            buffer![4i32, 5, 6, 7].into_array(),
560            buffer![0u32, 1, 4].into_array(),
561            Validity::NonNullable,
562        )
563        .unwrap()
564        .into_array();
565
566        let chunked =
567            ChunkedArray::try_new(vec![chunk0, chunk1], i32_list_dtype(false))?.into_array();
568
569        let layout = write(&ChunkedLayoutStrategy::new(flat_list_strategy()), chunked).await?;
570
571        insta::assert_snapshot!(layout.display_tree(), @"
572        vortex.chunked, dtype: list(i32), children: 2
573        ├── [0]: vortex.list, dtype: list(i32), children: 2
574        │   ├── elements: vortex.flat, dtype: i32, segment: 0
575        │   └── offsets: vortex.flat, dtype: u64, segment: 1
576        └── [1]: vortex.list, dtype: list(i32), children: 2
577            ├── elements: vortex.flat, dtype: i32, segment: 2
578            └── offsets: vortex.flat, dtype: u64, segment: 3
579        ");
580        Ok(())
581    }
582}