1use 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::ArrayContext;
11use vortex_array::ArrayRef;
12use vortex_array::ExecutionCtx;
13use vortex_array::IntoArray;
14use vortex_array::VortexSessionExecute;
15use vortex_array::arrays::ConstantArray;
16use vortex_array::arrays::List;
17use vortex_array::arrays::ListView;
18use vortex_array::arrays::PrimitiveArray;
19use vortex_array::arrays::list::ListDataParts;
20use vortex_array::arrays::listview::list_from_list_view;
21use vortex_array::builtins::ArrayBuiltins;
22use vortex_array::dtype::DType;
23use vortex_array::dtype::Nullability;
24use vortex_array::dtype::PType;
25use vortex_array::matcher::Matcher;
26use vortex_array::scalar_fn::fns::operators::Operator;
27use vortex_error::VortexExpect;
28use vortex_error::VortexResult;
29use vortex_error::vortex_bail;
30use vortex_io::kanal_ext::KanalExt;
31use vortex_io::session::RuntimeSessionExt;
32use vortex_session::VortexSession;
33
34use crate::LayoutRef;
35use crate::LayoutStrategy;
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
46type ChildChunk = VortexResult<(SequenceId, ArrayRef)>;
48
49#[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 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 pub fn with_elements(mut self, elements: Arc<dyn LayoutStrategy>) -> Self {
91 self.elements = elements;
92 self
93 }
94
95 pub fn with_offsets(mut self, offsets: Arc<dyn LayoutStrategy>) -> Self {
97 self.offsets = offsets;
98 self
99 }
100
101 pub fn with_validity(mut self, validity: Arc<dyn LayoutStrategy>) -> Self {
103 self.validity = validity;
104 self
105 }
106
107 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: ArrayContext,
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 let offsets_dtype = DType::Primitive(PType::U64, Nullability::NonNullable);
141
142 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 let fanout_fut = transpose_list_column(
156 stream,
157 session.clone(),
158 elements_tx,
159 offsets_tx,
160 validity_tx,
161 );
162
163 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 fn buffered_bytes(&self) -> u64 {
210 let list_bytes = self.elements.buffered_bytes()
211 + self.offsets.buffered_bytes()
212 + self.validity.buffered_bytes();
213 list_bytes.max(self.fallback.buffered_bytes())
214 }
215}
216
217async fn transpose_list_column(
224 mut stream: SendableSequentialStream,
225 session: VortexSession,
226 elements_tx: kanal::AsyncSender<ChildChunk>,
227 offsets_tx: kanal::AsyncSender<ChildChunk>,
228 validity_tx: Option<kanal::AsyncSender<ChildChunk>>,
229) -> VortexResult<()> {
230 let mut exec_ctx = session.create_execution_ctx();
231 let mut element_base: u64 = 0;
232 let mut first = true;
233 let mut saw_chunk = false;
234 while let Some(chunk) = stream.next().await {
235 let (sequence_id, array) = chunk?;
236 saw_chunk = true;
237 let mut sp = sequence_id.descend();
238 let ListDataParts {
239 elements,
240 offsets,
241 validity,
242 ..
243 } = canonicalize_to_list_parts(array, &mut exec_ctx)?;
244 let n_elements = elements.len() as u64;
245 let row_count = offsets.len().saturating_sub(1);
246 let offsets = global_offsets(offsets, element_base, first, &mut exec_ctx)?;
247 element_base += n_elements;
248 first = false;
249
250 if elements_tx
251 .send(Ok((sp.advance(), elements)))
252 .await
253 .is_err()
254 || offsets_tx.send(Ok((sp.advance(), offsets))).await.is_err()
255 {
256 vortex_bail!("list child writer finished before all chunks were sent");
257 }
258 if let Some(validity_tx) = &validity_tx {
259 let validity = validity
260 .execute_mask(row_count, &mut exec_ctx)?
261 .into_array();
262 if validity_tx
263 .send(Ok((sp.advance(), validity)))
264 .await
265 .is_err()
266 {
267 vortex_bail!("list validity writer finished before all chunks were sent");
268 }
269 }
270 }
271 if !saw_chunk {
272 vortex_bail!("ListLayoutStrategy needs at least one chunk");
273 }
274 Ok(())
275}
276
277fn canonicalize_to_list_parts(
279 array: ArrayRef,
280 exec_ctx: &mut ExecutionCtx,
281) -> VortexResult<ListDataParts> {
282 let canonical = array.execute_until::<AnyList>(exec_ctx)?;
283 if let Some(list) = canonical.as_opt::<List>() {
284 Ok(list.into_owned().into_data_parts())
285 } else if let Some(view) = canonical.as_opt::<ListView>() {
286 Ok(list_from_list_view(view.into_owned(), exec_ctx)?.into_data_parts())
287 } else {
288 unreachable!("AnyList matcher guarantees List or ListView")
289 }
290}
291
292fn global_offsets(
298 offsets: ArrayRef,
299 element_base: u64,
300 first: bool,
301 exec_ctx: &mut ExecutionCtx,
302) -> VortexResult<ArrayRef> {
303 let widened = offsets.cast(DType::Primitive(PType::U64, Nullability::NonNullable))?;
304 let based = if element_base == 0 {
305 widened
306 } else {
307 let base = ConstantArray::new(element_base, widened.len()).into_array();
308 widened.binary(base, Operator::Add)?
309 };
310 let based = if first {
311 based
312 } else {
313 based.slice(1..based.len())?
314 };
315 Ok(based.execute::<PrimitiveArray>(exec_ctx)?.into_array())
317}
318
319struct AnyList;
321
322impl Matcher for AnyList {
323 type Match<'a> = ();
324
325 fn try_match(array: &ArrayRef) -> Option<Self::Match<'_>> {
326 (array.as_opt::<List>().is_some() || array.as_opt::<ListView>().is_some()).then_some(())
327 }
328}
329
330#[cfg(test)]
331mod tests {
332 use futures::stream;
333 use vortex_array::arrays::BoolArray;
334 use vortex_array::arrays::ChunkedArray;
335 use vortex_array::arrays::ListArray;
336 use vortex_array::arrays::StructArray;
337 use vortex_array::dtype::Nullability;
338 use vortex_array::dtype::PType;
339 use vortex_array::validity::Validity;
340 use vortex_buffer::buffer;
341 use vortex_io::session::RuntimeSession;
342
343 use super::*;
344 use crate::layouts::chunked::writer::ChunkedLayoutStrategy;
345 use crate::layouts::flat::writer::FlatLayoutStrategy;
346 use crate::layouts::table::TableStrategy;
347 use crate::segments::TestSegments;
348 use crate::sequence::SequentialArrayStreamExt;
349 use crate::session::LayoutSession;
350
351 fn layout_test_session() -> VortexSession {
352 vortex_array::array_session()
353 .with::<LayoutSession>()
354 .with::<RuntimeSession>()
355 .with_tokio()
356 }
357
358 fn flat_list_strategy() -> ListLayoutStrategy {
359 ListLayoutStrategy::default()
360 }
361
362 async fn write<S: LayoutStrategy>(strategy: &S, array: ArrayRef) -> VortexResult<LayoutRef> {
363 let session = layout_test_session();
364 let segments = Arc::new(TestSegments::default());
365 let (ptr, eof) = SequenceId::root().split();
366 let stream = array.to_array_stream().sequenced(ptr);
367 strategy
368 .write_stream(ArrayContext::empty(), segments, stream, eof, &session)
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 #[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(ArrayContext::empty(), segments, stream, eof, &session)
445 .await;
446 assert!(res.is_err())
447 }
448
449 #[tokio::test]
450 async fn list_of_struct_tree() -> VortexResult<()> {
451 let struct_array = StructArray::from_fields(
452 [
453 ("a", buffer![1i32, 2, 3, 4, 5].into_array()),
454 ("b", buffer![10i32, 20, 30, 40, 50].into_array()),
455 ]
456 .as_slice(),
457 )?
458 .into_array();
459 let list = ListArray::try_new(
460 struct_array,
461 buffer![0u32, 2, 5, 5].into_array(),
462 Validity::NonNullable,
463 )?
464 .into_array();
465
466 let flat: Arc<dyn LayoutStrategy> = Arc::new(FlatLayoutStrategy::default());
467 let table_strategy: Arc<dyn LayoutStrategy> =
468 Arc::new(TableStrategy::new(Arc::clone(&flat), Arc::clone(&flat)));
469 let writer = ListLayoutStrategy::default().with_elements(table_strategy);
470
471 let layout = write(&writer, list).await?;
472 insta::assert_snapshot!(layout.display_tree(), @"
473 vortex.list, dtype: list({a=i32, b=i32}), children: 2
474 ├── elements: vortex.struct, dtype: {a=i32, b=i32}, children: 2
475 │ ├── a: vortex.flat, dtype: i32, segment: 1
476 │ └── b: vortex.flat, dtype: i32, segment: 2
477 └── offsets: vortex.flat, dtype: u64, segment: 0
478 ");
479 Ok(())
480 }
481
482 #[tokio::test]
483 async fn list_of_list_tree() -> VortexResult<()> {
484 let inner_list = ListArray::try_new(
485 buffer![1i32, 2, 3, 4, 5, 6].into_array(),
486 buffer![0u32, 2, 5, 5, 6].into_array(),
487 Validity::NonNullable,
488 )?
489 .into_array();
490 let list = ListArray::try_new(
491 inner_list,
492 buffer![0u32, 2, 4].into_array(),
493 Validity::NonNullable,
494 )?
495 .into_array();
496
497 let writer =
498 ListLayoutStrategy::default().with_elements(Arc::new(ListLayoutStrategy::default()));
499 let layout = write(&writer, list).await?;
500 insta::assert_snapshot!(layout.display_tree(), @"
501 vortex.list, dtype: list(list(i32)), children: 2
502 ├── elements: vortex.list, dtype: list(i32), children: 2
503 │ ├── elements: vortex.flat, dtype: i32, segment: 1
504 │ └── offsets: vortex.flat, dtype: u64, segment: 2
505 └── offsets: vortex.flat, dtype: u64, segment: 0
506 ");
507 Ok(())
508 }
509
510 #[tokio::test]
511 async fn list_of_list_of_list_tree() -> VortexResult<()> {
512 let innermost = ListArray::try_new(
513 buffer![1i32, 2, 3, 4].into_array(),
514 buffer![0u32, 2, 4].into_array(),
515 Validity::NonNullable,
516 )?
517 .into_array();
518 let middle = ListArray::try_new(
519 innermost,
520 buffer![0u32, 2].into_array(),
521 Validity::NonNullable,
522 )?
523 .into_array();
524 let outer =
525 ListArray::try_new(middle, buffer![0u32, 1].into_array(), Validity::NonNullable)?
526 .into_array();
527
528 let writer = ListLayoutStrategy::default().with_elements(Arc::new(
529 ListLayoutStrategy::default().with_elements(Arc::new(ListLayoutStrategy::default())),
530 ));
531 let layout = write(&writer, outer).await?;
532 insta::assert_snapshot!(layout.display_tree(), @"
533 vortex.list, dtype: list(list(list(i32))), children: 2
534 ├── elements: vortex.list, dtype: list(list(i32)), children: 2
535 │ ├── elements: vortex.list, dtype: list(i32), children: 2
536 │ │ ├── elements: vortex.flat, dtype: i32, segment: 2
537 │ │ └── offsets: vortex.flat, dtype: u64, segment: 3
538 │ └── offsets: vortex.flat, dtype: u64, segment: 1
539 └── offsets: vortex.flat, dtype: u64, segment: 0
540 ");
541 Ok(())
542 }
543
544 #[tokio::test]
545 async fn chunked_list_input_with_chunked_strategy_succeeds() -> VortexResult<()> {
546 let chunk0 = ListArray::try_new(
547 buffer![1i32, 2, 3].into_array(),
548 buffer![0u32, 2, 3].into_array(),
549 Validity::NonNullable,
550 )
551 .unwrap()
552 .into_array();
553 let chunk1 = ListArray::try_new(
554 buffer![4i32, 5, 6, 7].into_array(),
555 buffer![0u32, 1, 4].into_array(),
556 Validity::NonNullable,
557 )
558 .unwrap()
559 .into_array();
560
561 let chunked =
562 ChunkedArray::try_new(vec![chunk0, chunk1], i32_list_dtype(false))?.into_array();
563
564 let layout = write(&ChunkedLayoutStrategy::new(flat_list_strategy()), chunked).await?;
565
566 insta::assert_snapshot!(layout.display_tree(), @"
567 vortex.chunked, dtype: list(i32), children: 2
568 ├── [0]: vortex.list, dtype: list(i32), children: 2
569 │ ├── elements: vortex.flat, dtype: i32, segment: 0
570 │ └── offsets: vortex.flat, dtype: u64, segment: 1
571 └── [1]: vortex.list, dtype: list(i32), children: 2
572 ├── elements: vortex.flat, dtype: i32, segment: 2
573 └── offsets: vortex.flat, dtype: u64, segment: 3
574 ");
575 Ok(())
576 }
577}