Skip to main content

vortex_array/arrays/chunked/compute/
take.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use itertools::Itertools;
5use vortex_buffer::Buffer;
6use vortex_buffer::BufferAllocatorRef;
7use vortex_buffer::BufferMut;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10use vortex_error::vortex_ensure_eq;
11use vortex_error::vortex_err;
12use vortex_mask::Mask;
13use vortex_utils::aliases::hash_map::HashMap;
14
15use crate::ArrayRef;
16use crate::Canonical;
17use crate::Columnar;
18use crate::IntoArray;
19use crate::array::ArrayView;
20use crate::arrays::Chunked;
21use crate::arrays::ChunkedArray;
22use crate::arrays::FixedSizeList;
23use crate::arrays::FixedSizeListArray;
24use crate::arrays::PiecewiseSequence;
25use crate::arrays::PrimitiveArray;
26use crate::arrays::Slice;
27use crate::arrays::Struct;
28use crate::arrays::StructArray;
29use crate::arrays::chunked::ChunkedArrayExt;
30use crate::arrays::dict::TakeExecute;
31use crate::arrays::piecewise_sequence::constant_unsigned_usize;
32use crate::arrays::piecewise_sequence::contiguous_runs;
33use crate::arrays::piecewise_sequence::maybe_contiguous_slices;
34use crate::arrays::primitive::PrimitiveArrayExt;
35use crate::arrays::struct_::StructArrayExt;
36use crate::builders::ArrayBuilder;
37use crate::builders::builder_with_capacity_in;
38use crate::builtins::ArrayBuiltins;
39use crate::dtype::DType;
40use crate::dtype::PType;
41use crate::dtype::UnsignedPType;
42use crate::executor::Executable;
43use crate::executor::ExecutionCtx;
44use crate::match_each_unsigned_integer_ptype;
45use crate::optimizer::ArrayOptimizer;
46use crate::validity::Validity;
47
48/// Flattens per-chunk take/filter results into a single array. Flat dtypes append directly into
49/// a canonical builder; nested dtypes collect the chunks and canonicalize them as a chunked
50/// array, which reuses the chunks' children zero-copy.
51enum ChunkFlattener {
52    Builder(Box<dyn ArrayBuilder>),
53    Chunks(Vec<ArrayRef>),
54}
55
56impl ChunkFlattener {
57    fn new(dtype: &DType, capacity: usize, allocator: &BufferAllocatorRef) -> Self {
58        if dtype.is_nested() {
59            Self::Chunks(Vec::new())
60        } else {
61            Self::Builder(builder_with_capacity_in(dtype, capacity, allocator))
62        }
63    }
64
65    fn push(&mut self, chunk: ArrayRef, ctx: &mut ExecutionCtx) -> VortexResult<()> {
66        match self {
67            Self::Builder(builder) => chunk.append_to_builder(builder.as_mut(), ctx),
68            Self::Chunks(chunks) => {
69                chunks.push(chunk);
70                Ok(())
71            }
72        }
73    }
74
75    fn finish(self, dtype: &DType, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
76        match self {
77            Self::Builder(mut builder) => Ok(builder.finish()),
78            // SAFETY: every chunk is a filter or take of a chunk of a chunked array with `dtype`,
79            // which leaves the dtype unchanged.
80            Self::Chunks(chunks) => unsafe { ChunkedArray::new_unchecked(chunks, dtype.clone()) }
81                .into_array()
82                .execute::<Canonical>(ctx)
83                .map(IntoArray::into_array),
84        }
85    }
86}
87
88fn take_chunked_via_sort(
89    array: ArrayView<'_, Chunked>,
90    indices: &PrimitiveArray,
91    indices_mask: Mask,
92    ctx: &mut ExecutionCtx,
93) -> VortexResult<ArrayRef> {
94    let indices_values = indices.as_slice::<u64>();
95    let n = indices_values.len();
96    let mut pairs: Vec<(u64, usize)> = indices_values
97        .iter()
98        .enumerate()
99        .filter(|&(position, _)| indices_mask.value(position))
100        .map(|(position, &index)| (index, position))
101        .collect();
102    pairs.sort_unstable();
103
104    if let Some(&(index, _)) = pairs.last() {
105        let index = usize::try_from(index)?;
106        if index >= array.len() {
107            vortex_bail!(
108                "index {} out of bounds from {} to {}",
109                index,
110                0,
111                array.len()
112            );
113        }
114    }
115
116    let chunk_offsets = array.chunk_offset_values();
117    let nchunks = array.nchunks();
118    let mut flattener = ChunkFlattener::new(array.dtype(), pairs.len(), ctx.allocator());
119    let mut final_take = BufferMut::<u64>::zeroed(n);
120    let mut cursor = 0usize;
121    let mut dedup_idx = 0u64;
122
123    for chunk_idx in 0..nchunks {
124        let chunk_start = chunk_offsets[chunk_idx];
125        let chunk_end = chunk_offsets[chunk_idx + 1];
126        let chunk_len = chunk_end - chunk_start;
127        let chunk_end_u64 = u64::try_from(chunk_end)?;
128        let range_end = cursor + pairs[cursor..].partition_point(|&(v, _)| v < chunk_end_u64);
129        let chunk_pairs = &pairs[cursor..range_end];
130
131        if !chunk_pairs.is_empty() {
132            let mut local_indices = Vec::new();
133            for (i, &(value, original_position)) in chunk_pairs.iter().enumerate() {
134                if cursor + i > 0 && value != pairs[cursor + i - 1].0 {
135                    dedup_idx += 1;
136                }
137                let local_index = usize::try_from(value)? - chunk_start;
138                if local_indices.last() != Some(&local_index) {
139                    local_indices.push(local_index);
140                }
141                final_take[original_position] = dedup_idx;
142            }
143
144            flattener.push(
145                array
146                    .chunk(chunk_idx)
147                    .filter(Mask::from_indices(chunk_len, local_indices))?,
148                ctx,
149            )?;
150        }
151
152        cursor = range_end;
153    }
154
155    let flat = flattener.finish(array.dtype(), ctx)?;
156    let take_validity = Validity::from_mask(indices_mask, indices.dtype().nullability());
157    flat.take(PrimitiveArray::new(final_take.freeze(), take_validity).into_array())
158}
159
160fn valid_indices_are_monotonic(indices: &[u64], indices_mask: &Mask) -> bool {
161    let mut previous = None;
162    for (position, &index) in indices.iter().enumerate() {
163        if !indices_mask.value(position) {
164            continue;
165        }
166        if previous.is_some_and(|previous| index < previous) {
167            return false;
168        }
169        previous = Some(index);
170    }
171    true
172}
173
174// TODO(joe): we want to return a chunked array ideally.
175fn take_chunked(
176    array: ArrayView<'_, Chunked>,
177    indices: &ArrayRef,
178    ctx: &mut ExecutionCtx,
179) -> VortexResult<ArrayRef> {
180    let indices = indices
181        .cast(DType::Primitive(PType::U64, indices.dtype().nullability()))?
182        .execute::<PrimitiveArray>(ctx)?;
183
184    let indices_mask = indices
185        .as_ref()
186        .validity()?
187        .execute_mask(indices.as_ref().len(), ctx)?;
188    let indices_values = indices.as_slice::<u64>();
189    let n = indices_values.len();
190    let chunk_offsets = array.chunk_offset_values();
191    let nchunks = array.nchunks();
192
193    // Strictly increasing non-nullable indices select every row at most once and in order, so the
194    // per-chunk gathers concatenate straight into the result with no dedup or reorder take.
195    if !indices.as_ref().dtype().is_nullable() && indices_values.is_sorted_by(|a, b| a < b) {
196        return take_chunked_sorted(array, indices_values);
197    }
198
199    // For a small unsorted fixed-size-list take over a small number of chunks, sorting has lower
200    // fixed overhead and lets the nested elements filter in source order. Larger, monotonic, and
201    // non-nested takes use bucketing.
202    if matches!(array.dtype(), DType::FixedSizeList(..))
203        && n <= 64
204        && nchunks <= 16
205        && !valid_indices_are_monotonic(indices_values, &indices_mask)
206    {
207        return take_chunked_via_sort(array, &indices, indices_mask, ctx);
208    }
209
210    // Route each valid index into its source chunk. Within each bucket, preserve the request order
211    // so the taken chunks can be assembled and then restored to the original cross-chunk order.
212    let mut buckets = vec![Vec::<(u64, usize)>::new(); nchunks];
213    let mut monotonic = true;
214    let mut last_index = None;
215    let mut sorted_chunk_idx = 0;
216
217    for (original_position, &index) in indices_values.iter().enumerate() {
218        if !indices_mask.value(original_position) {
219            continue;
220        }
221
222        let index = usize::try_from(index)?;
223        if index >= array.len() {
224            vortex_bail!(
225                "index {} out of bounds from {} to {}",
226                index,
227                0,
228                array.len()
229            );
230        }
231
232        let still_sorted = last_index.is_none_or(|last_index| index >= last_index);
233        let chunk_idx = if monotonic && still_sorted {
234            while chunk_offsets[sorted_chunk_idx + 1] <= index {
235                sorted_chunk_idx += 1;
236            }
237            sorted_chunk_idx
238        } else {
239            monotonic = false;
240            chunk_offsets.partition_point(|&offset| offset <= index) - 1
241        };
242        last_index = Some(index);
243
244        let local_index = u64::try_from(index - chunk_offsets[chunk_idx])?;
245        buckets[chunk_idx].push((local_index, original_position));
246    }
247
248    let mut flattener =
249        ChunkFlattener::new(array.dtype(), indices_mask.true_count(), ctx.allocator());
250    let mut final_take =
251        (!monotonic || indices.dtype().is_nullable()).then(|| BufferMut::<u64>::zeroed(n));
252    let mut grouped_position = 0u64;
253
254    for (chunk_idx, bucket) in buckets.into_iter().enumerate() {
255        if bucket.is_empty() {
256            continue;
257        }
258
259        let mut local_indices = BufferMut::<u64>::with_capacity(bucket.len());
260        for (local_index, original_position) in bucket {
261            local_indices.push(local_index);
262            if let Some(final_take) = &mut final_take {
263                final_take[original_position] = grouped_position;
264            }
265            grouped_position += 1;
266        }
267
268        let local_indices =
269            PrimitiveArray::new(local_indices.freeze(), Validity::NonNullable).into_array();
270        flattener.push(array.chunk(chunk_idx).take(local_indices)?, ctx)?;
271    }
272
273    // TODO(joe): can we relax this.
274    let flat = flattener.finish(array.dtype(), ctx)?;
275
276    // Non-nullable monotonic indices are already in the same order as the assembled chunks, so no
277    // final reorder is needed.
278    let Some(final_take) = final_take else {
279        return Ok(flat);
280    };
281
282    // A single take restores original order and expands duplicates. Carrying the original index
283    // validity makes null indices produce null outputs.
284    let take_validity = Validity::from_mask(indices_mask, indices.dtype().nullability());
285    flat.take(PrimitiveArray::new(final_take.freeze(), take_validity).into_array())
286}
287
288/// Take for strictly increasing, non-nullable indices: every row is selected at most once and in
289/// order, so the per-chunk gathers concatenate directly into the result with no bucketing, dedup,
290/// or reorder take.
291fn take_chunked_sorted(
292    array: ArrayView<'_, Chunked>,
293    indices_values: &[u64],
294) -> VortexResult<ArrayRef> {
295    let chunk_offsets = array.chunk_offset_values();
296    let mut chunks = Vec::new();
297    let mut cursor = 0usize;
298
299    // Skip straight to the chunk holding the first index instead of walking every leading chunk;
300    // `<=` steps past empty chunks sharing the same offset.
301    let first_chunk = match indices_values.first() {
302        Some(&first) => {
303            let first = usize::try_from(first)?;
304            chunk_offsets
305                .partition_point(|&offset| offset <= first)
306                .saturating_sub(1)
307        }
308        None => 0,
309    };
310
311    for chunk_idx in first_chunk..array.nchunks() {
312        if cursor == indices_values.len() {
313            break;
314        }
315        let chunk_start = chunk_offsets[chunk_idx];
316        let chunk_end = chunk_offsets[chunk_idx + 1];
317        let chunk_end_u64 = u64::try_from(chunk_end)?;
318
319        let range_end = cursor + indices_values[cursor..].partition_point(|&v| v < chunk_end_u64);
320        if range_end > cursor {
321            let chunk_start_u64 = u64::try_from(chunk_start)?;
322            let mut local_indices = BufferMut::<u64>::with_capacity(range_end - cursor);
323            for &val in &indices_values[cursor..range_end] {
324                local_indices.push(val - chunk_start_u64);
325            }
326            let local_indices =
327                PrimitiveArray::new(local_indices.freeze(), Validity::NonNullable).into_array();
328            chunks.push(array.chunk(chunk_idx).take(local_indices)?);
329        }
330        cursor = range_end;
331    }
332    if cursor != indices_values.len() {
333        vortex_bail!(
334            "index {} out of bounds from {} to {}",
335            usize::try_from(indices_values[cursor])?,
336            0,
337            array.as_ref().len()
338        );
339    }
340
341    if chunks.len() == 1 {
342        return Ok(chunks.swap_remove(0));
343    }
344    // SAFETY: every chunk is a take of a chunk of `array` with non-nullable indices, which
345    // leaves the dtype unchanged.
346    Ok(unsafe { ChunkedArray::new_unchecked(chunks, array.dtype().clone()) }.into_array())
347}
348
349impl TakeExecute for Chunked {
350    fn take(
351        array: ArrayView<'_, Chunked>,
352        indices: &ArrayRef,
353        ctx: &mut ExecutionCtx,
354    ) -> VortexResult<Option<ArrayRef>> {
355        if array.nchunks() == 1 {
356            return array.chunk(0).take(indices.clone()).map(Some);
357        }
358
359        if let Some(taken) = take_chunked_fsl(array, indices, ctx)? {
360            return Ok(Some(taken));
361        }
362
363        if let Some(taken) = take_chunked_struct(array, indices, ctx)? {
364            return Ok(Some(taken));
365        }
366
367        if let Some(piecewise_indices) = indices.as_opt::<PiecewiseSequence>()
368            && let Some(taken) = take_piecewise_chunked(array, piecewise_indices, ctx)?
369        {
370            return Ok(Some(taken));
371        }
372
373        take_chunked(array, indices, ctx).map(Some)
374    }
375}
376
377/// Rewrites take over a chunked fixed-size list array as take over a single
378/// [`FixedSizeListArray`]. The swizzle is structural: FSL-encoded chunks execute to themselves,
379/// so their elements chain zero-copy, and the FSL take then gathers per-chunk element runs
380/// instead of taking each chunk.
381fn take_chunked_fsl(
382    array: ArrayView<'_, Chunked>,
383    indices: &ArrayRef,
384    ctx: &mut ExecutionCtx,
385) -> VortexResult<Option<ArrayRef>> {
386    if !matches!(array.dtype(), DType::FixedSizeList(..)) {
387        return Ok(None);
388    }
389
390    let Some((array, indices)) = touched_chunks(array, indices, ctx)? else {
391        let fsl = array.as_ref().clone().execute::<FixedSizeListArray>(ctx)?;
392        return fsl.into_array().take(indices.clone()).map(Some);
393    };
394
395    take_swizzled::<FixedSizeListArray>(array, indices, ctx).map(Some)
396}
397
398/// Rewrites take over a chunked struct array with a fixed-size-list field as take over a single
399/// [`StructArray`] whose fields are chunked. The swizzle is structural: it needs no decode when
400/// every chunk is already a struct, which is the case for the chunks of a file scan. Each
401/// fixed-size-list field then takes once with the element-run gather of [`take_chunked_fsl`],
402/// instead of a struct take and a list take for each chunk that the indices touch.
403///
404/// Structs without a fixed-size-list field keep the per-chunk take: there, each field would route
405/// the indices to the chunks again, which costs more than the struct take of each chunk.
406fn take_chunked_struct(
407    array: ArrayView<'_, Chunked>,
408    indices: &ArrayRef,
409    ctx: &mut ExecutionCtx,
410) -> VortexResult<Option<ArrayRef>> {
411    let DType::Struct(fields, _) = array.dtype() else {
412        return Ok(None);
413    };
414
415    if !fields
416        .fields()
417        .any(|field| matches!(field, DType::FixedSizeList(..)))
418    {
419        return Ok(None);
420    }
421
422    // A chunk with another encoding would have to execute to a struct, which can decode the whole
423    // chunk to take a few rows of it. Only the chunks that the swizzle visits must be structs.
424    match touched_chunks(array, indices, ctx)? {
425        Some((chunks, indices)) => {
426            if !chunks.iter().all(is_swizzle_ready_struct) {
427                return Ok(None);
428            }
429            take_swizzled::<StructArray>(chunks, indices, ctx).map(Some)
430        }
431        None => {
432            if !array.iter_chunks().all(is_swizzle_ready_struct) {
433                return Ok(None);
434            }
435            let structs = array.as_ref().clone().execute::<StructArray>(ctx)?;
436            structs.into_array().take(indices.clone()).map(Some)
437        }
438    }
439}
440
441/// Returns true if `chunk` is a struct whose fixed-size-list fields are all FSL-encoded.
442///
443/// The list take of the swizzled struct executes each chunk of a fixed-size-list field to a
444/// [`FixedSizeListArray`] before it selects rows. For another encoding, for example a dictionary,
445/// this decodes all rows of the chunk. The per-chunk take selects the rows first, for example only
446/// the dictionary codes, so these chunks use it.
447fn is_swizzle_ready_struct(chunk: &ArrayRef) -> bool {
448    let Some(struct_chunk) = chunk.as_opt::<Struct>() else {
449        return false;
450    };
451
452    struct_chunk
453        .struct_fields()
454        .fields()
455        .enumerate()
456        .filter(|(_, dtype)| matches!(dtype, DType::FixedSizeList(..)))
457        .all(|(idx, _)| struct_chunk.unmasked_field(idx).is::<FixedSizeList>())
458}
459
460/// Takes `indices` from `chunks` through one swizzled array of type `A`, or directly from the
461/// chunk when there is only one.
462fn take_swizzled<A>(
463    chunks: Vec<ArrayRef>,
464    indices: ArrayRef,
465    ctx: &mut ExecutionCtx,
466) -> VortexResult<ArrayRef>
467where
468    A: Executable + IntoArray,
469{
470    if let [chunk] = chunks.as_slice() {
471        return chunk.take(indices);
472    }
473
474    let dtype = chunks[0].dtype().clone();
475    // SAFETY: the chunks are chunks of one chunked array, so they all have its dtype.
476    let swizzled = unsafe { ChunkedArray::new_unchecked(chunks, dtype) }
477        .into_array()
478        .execute::<A>(ctx)?;
479    swizzled.into_array().take(indices)
480}
481
482/// The chunks that the non-nullable `indices` touch, in chunk order, and the indices into them.
483///
484/// A swizzle of a chunked array visits every chunk, so a small take over many chunks first keeps
485/// only the chunks that it reads. Returns `None` for nullable indices and for indices that touch
486/// every chunk.
487fn touched_chunks(
488    array: ArrayView<'_, Chunked>,
489    indices: &ArrayRef,
490    ctx: &mut ExecutionCtx,
491) -> VortexResult<Option<(Vec<ArrayRef>, ArrayRef)>> {
492    if indices.dtype().is_nullable() || indices.is_empty() {
493        return Ok(None);
494    }
495
496    if let Some(piecewise) = indices.as_opt::<PiecewiseSequence>()
497        && let Some((starts, lengths)) = maybe_contiguous_slices(piecewise, ctx)?
498    {
499        return touched_chunks_piecewise(array, piecewise, &starts, lengths);
500    }
501
502    let indices = indices
503        .cast(DType::Primitive(PType::U64, indices.dtype().nullability()))?
504        .execute::<PrimitiveArray>(ctx)?;
505    let indices = indices.as_slice::<u64>();
506    let chunk_offsets = array.chunk_offset_values();
507    let array_len = array.as_ref().len();
508
509    // `<=` steps past empty chunks that share the offset of the next chunk.
510    let index_chunks = indices
511        .iter()
512        .map(|&index| -> VortexResult<usize> {
513            let index = usize::try_from(index)?;
514            if index >= array_len {
515                vortex_bail!("index {} out of bounds from {} to {}", index, 0, array_len);
516            }
517            Ok(chunk_offsets.partition_point(|&offset| offset <= index) - 1)
518        })
519        .collect::<VortexResult<Vec<_>>>()?;
520
521    let mut touched = index_chunks.clone();
522    touched.sort_unstable();
523    touched.dedup();
524
525    if touched.len() == array.nchunks() {
526        return Ok(None);
527    }
528
529    let touched_offsets = touched_chunk_offsets(chunk_offsets, &touched);
530    let remapped = indices
531        .iter()
532        .zip_eq(index_chunks)
533        .map(|(&index, chunk_idx)| -> VortexResult<u64> {
534            let position = touched
535                .binary_search(&chunk_idx)
536                .map_err(|_| vortex_err!("chunk {chunk_idx} is not a touched chunk"))?;
537            let local = usize::try_from(index)? - chunk_offsets[chunk_idx];
538            Ok(u64::try_from(touched_offsets[position] + local)?)
539        })
540        .collect::<VortexResult<Buffer<u64>>>()?;
541
542    let chunks = touched
543        .iter()
544        .map(|&chunk_idx| array.chunk(chunk_idx).clone())
545        .collect();
546    Ok(Some((
547        chunks,
548        PrimitiveArray::new(remapped, Validity::NonNullable).into_array(),
549    )))
550}
551
552/// Computes touched chunks and remapped [`PiecewiseSequence`] indices directly from contiguous
553/// runs without expanding them.
554fn touched_chunks_piecewise(
555    array: ArrayView<'_, Chunked>,
556    indices: ArrayView<'_, PiecewiseSequence>,
557    starts: &PrimitiveArray,
558    lengths: Columnar,
559) -> VortexResult<Option<(Vec<ArrayRef>, ArrayRef)>> {
560    let output_len = indices.as_ref().len();
561    let sub_pieces = split_piecewise_runs(array, starts, lengths, output_len)?;
562
563    let mut touched: Vec<usize> = sub_pieces
564        .iter()
565        .map(|&(chunk_idx, ..)| chunk_idx)
566        .collect();
567    touched.sort_unstable();
568    touched.dedup();
569    if touched.len() == array.nchunks() {
570        return Ok(None);
571    }
572
573    let touched_offsets = touched_chunk_offsets(array.chunk_offset_values(), &touched);
574    let mut remapped_starts = Vec::with_capacity(sub_pieces.len());
575    let mut remapped_lengths = Vec::with_capacity(sub_pieces.len());
576    for (chunk_idx, local_start, run) in sub_pieces {
577        let position = touched
578            .binary_search(&chunk_idx)
579            .map_err(|_| vortex_err!("chunk {chunk_idx} is not a touched chunk"))?;
580        let remapped_start = u64::try_from(touched_offsets[position] + local_start)?;
581        let remapped_len = u64::try_from(run)?;
582        match (remapped_starts.last(), remapped_lengths.last_mut()) {
583            (Some(&prev_start), Some(prev_len)) if prev_start + *prev_len == remapped_start => {
584                *prev_len += remapped_len;
585            }
586            _ => {
587                remapped_starts.push(remapped_start);
588                remapped_lengths.push(remapped_len);
589            }
590        }
591    }
592
593    let chunks = touched
594        .iter()
595        .map(|&chunk_idx| array.chunk(chunk_idx).clone())
596        .collect();
597    Ok(Some((
598        chunks,
599        contiguous_runs(remapped_starts, remapped_lengths, output_len),
600    )))
601}
602
603/// The offset of each touched chunk in the compacted touched-chunks array.
604fn touched_chunk_offsets(chunk_offsets: &[usize], touched: &[usize]) -> Vec<usize> {
605    let mut touched_offsets = Vec::with_capacity(touched.len());
606    let mut offset = 0usize;
607    for &chunk_idx in touched {
608        touched_offsets.push(offset);
609        offset += chunk_offsets[chunk_idx + 1] - chunk_offsets[chunk_idx];
610    }
611    touched_offsets
612}
613
614fn unsigned_slice_as_usize<T: UnsignedPType>(array: &PrimitiveArray) -> Vec<usize> {
615    array
616        .as_slice::<T>()
617        .iter()
618        .map(|&value| value.as_())
619        .collect()
620}
621
622fn contiguous_slice_ranges(starts: &PrimitiveArray, lengths: Columnar) -> (Vec<usize>, Vec<usize>) {
623    let starts = match_each_unsigned_integer_ptype!(starts.ptype(), |S| {
624        unsigned_slice_as_usize::<S>(starts)
625    });
626    let lengths = match lengths {
627        Columnar::Constant(lengths) => vec![constant_unsigned_usize(&lengths); starts.len()],
628        Columnar::Canonical(lengths) => {
629            let lengths = lengths.into_primitive();
630            match_each_unsigned_integer_ptype!(lengths.ptype(), |L| {
631                unsigned_slice_as_usize::<L>(&lengths)
632            })
633        }
634    };
635    (starts, lengths)
636}
637
638/// Splits contiguous [`PiecewiseSequence`] runs at chunk boundaries into
639/// `(chunk_idx, local_start, run)` sub-pieces in output order, validating bounds and total length.
640fn split_piecewise_runs(
641    array: ArrayView<'_, Chunked>,
642    starts: &PrimitiveArray,
643    lengths: Columnar,
644    output_len: usize,
645) -> VortexResult<Vec<(usize, usize, usize)>> {
646    let (starts, lengths) = contiguous_slice_ranges(starts, lengths);
647    let chunk_offsets = array.chunk_offset_values();
648    let array_len = array.as_ref().len();
649
650    let mut pieces = Vec::with_capacity(starts.len());
651    let mut total_len = 0usize;
652
653    for (&start, &length) in starts.iter().zip_eq(&lengths) {
654        if length == 0 {
655            continue;
656        }
657        let end = start
658            .checked_add(length)
659            .ok_or_else(|| vortex_err!("PiecewiseSequenceArray range overflows usize"))?;
660        if end > array_len {
661            vortex_bail!(
662                "index {} out of bounds from {} to {}",
663                end - 1,
664                0,
665                array_len
666            );
667        }
668        total_len = total_len
669            .checked_add(length)
670            .ok_or_else(|| vortex_err!("PiecewiseSequenceArray output length overflows usize"))?;
671
672        // Locate the chunk containing `start`; `<=` skips empty chunks sharing the same offset.
673        let mut chunk_idx = chunk_offsets.partition_point(|&offset| offset <= start) - 1;
674        let mut cursor = start;
675        let mut remaining = length;
676        while remaining > 0 {
677            while chunk_offsets[chunk_idx + 1] <= cursor {
678                chunk_idx += 1;
679            }
680            let run = remaining.min(chunk_offsets[chunk_idx + 1] - cursor);
681            pieces.push((chunk_idx, cursor - chunk_offsets[chunk_idx], run));
682            cursor += run;
683            remaining -= run;
684        }
685    }
686
687    vortex_ensure_eq!(
688        total_len,
689        output_len,
690        "PiecewiseSequenceArray expanded length does not match declared length",
691    );
692
693    Ok(pieces)
694}
695
696/// Out-of-order runs at least this long on average append to the result directly, in output
697/// order.
698///
699/// Each run is a slice of a chunk that appends into one builder, so the rows are decoded once.
700/// Each slice has a fixed cost, so for very short runs a second copy of the gathered rows costs
701/// about the same. In the `chunked_fsl_take` bench, the two paths are equal for runs of 16 rows,
702/// and the direct path is faster from 64 rows.
703const MIN_AVERAGE_DIRECT_RUN: usize = 32;
704
705/// Runs of a slice that does its work at execution append directly only if they are at least
706/// this long on average.
707const MIN_AVERAGE_EXECUTED_RUN: usize = 256;
708
709/// Runs of a slice that does its work at execution append directly only if they read at most
710/// `1 / SPARSE_CHUNK_RATIO` of the rows of each chunk.
711const SPARSE_CHUNK_RATIO: usize = 8;
712
713/// A per-chunk gather plan: chunk-local sub-piece runs to take from one chunk, in output order.
714#[derive(Default)]
715struct ChunkGather {
716    starts: Vec<u64>,
717    lengths: Vec<u64>,
718    total: usize,
719}
720
721/// Take for [`PiecewiseSequence`] indices with unit multipliers.
722///
723/// Each piece is a contiguous index run, so instead of expanding one index per element, pieces
724/// are split at chunk boundaries and gathered from each chunk with a chunk-local
725/// `PiecewiseSequenceArray`. Sub-pieces that visit chunks in non-decreasing order concatenate
726/// directly into the result; otherwise the gathered chunks are flattened once and a second
727/// piecewise take restores output order.
728fn take_piecewise_chunked(
729    array: ArrayView<'_, Chunked>,
730    indices: ArrayView<'_, PiecewiseSequence>,
731    ctx: &mut ExecutionCtx,
732) -> VortexResult<Option<ArrayRef>> {
733    let Some((starts, lengths)) = maybe_contiguous_slices(indices, ctx)? else {
734        return Ok(None);
735    };
736
737    let output_len = indices.as_ref().len();
738    let pieces = split_piecewise_runs(array, &starts, lengths, output_len)?;
739
740    // Plans exist only for the chunks that the pieces touch, in the order of the first visit, so
741    // the cost scales with the number of pieces and not with the number of chunks.
742    let mut plans: Vec<(usize, ChunkGather)> = Vec::new();
743    let mut plan_of_chunk: HashMap<usize, usize> = HashMap::default();
744    // Sub-pieces in output order: (plan index, offset within that chunk's gathered output, run
745    // length).
746    let mut sub_pieces: Vec<(usize, usize, usize)> = Vec::with_capacity(pieces.len());
747    // Sub-pieces in output order as (chunk index, start in the chunk, run length). A run that
748    // continues the previous run in the same chunk extends it.
749    let mut runs: Vec<(usize, usize, usize)> = Vec::with_capacity(pieces.len());
750    let mut monotonic = true;
751    let mut prev_chunk = 0usize;
752
753    for (chunk_idx, local_start, run) in pieces {
754        monotonic &= chunk_idx >= prev_chunk;
755        prev_chunk = chunk_idx;
756
757        // Consecutive sub-pieces usually stay in one chunk, so check the last plan first.
758        let plan_idx = match plans.last() {
759            Some((last_chunk, _)) if *last_chunk == chunk_idx => plans.len() - 1,
760            _ => *plan_of_chunk.entry(chunk_idx).or_insert_with(|| {
761                plans.push((chunk_idx, ChunkGather::default()));
762                plans.len() - 1
763            }),
764        };
765        let plan = &mut plans[plan_idx].1;
766
767        // Consecutive sub-pieces in the same chunk stay adjacent in its gathered output, so
768        // they merge into one reorder run.
769        match sub_pieces.last_mut() {
770            Some((last_plan, _, last_run)) if *last_plan == plan_idx => *last_run += run,
771            _ => sub_pieces.push((plan_idx, plan.total, run)),
772        }
773        // A run that continues exactly where the chunk's previous run ended extends it, so
774        // contiguous spans gather as one run.
775        match runs.last_mut() {
776            Some((last_chunk, last_start, last_run))
777                if *last_chunk == chunk_idx && *last_start + *last_run == local_start =>
778            {
779                *last_run += run;
780            }
781            _ => runs.push((chunk_idx, local_start, run)),
782        }
783
784        let local_start = local_start as u64;
785        match (plan.starts.last(), plan.lengths.last_mut()) {
786            (Some(&prev_start), Some(prev_len)) if prev_start + *prev_len == local_start => {
787                *prev_len += run as u64;
788            }
789            _ => {
790                plan.starts.push(local_start);
791                plan.lengths.push(run as u64);
792            }
793        }
794        plan.total += run;
795    }
796
797    // Chunks visited in order: the plans are in chunk order, and the per-chunk gathers already
798    // concatenate into the result.
799    if monotonic {
800        let mut gathered = Vec::with_capacity(plans.len());
801        for (chunk_idx, plan) in plans {
802            gathered.push(gather_chunk(array.chunk(chunk_idx), plan)?);
803        }
804        let result = if gathered.len() == 1 {
805            gathered.swap_remove(0)
806        } else {
807            // SAFETY: every gathered chunk is a take of a chunk with dtype `array.dtype()`, and
808            // the non-nullable piecewise indices leave the dtype unchanged.
809            unsafe { ChunkedArray::new_unchecked(gathered, array.dtype().clone()) }.into_array()
810        };
811        return Ok(Some(result));
812    }
813
814    // Long out-of-order runs: append a slice of each run to the result in output order, so the
815    // rows are decoded once and copied once.
816    if !array.dtype().is_nested()
817        && output_len >= runs.len() * MIN_AVERAGE_DIRECT_RUN
818        && (sparse_long_runs(array, &plans, runs.len(), output_len)
819            || slices_reduce(array, &runs, ctx)?)
820    {
821        let mut flattener = ChunkFlattener::new(array.dtype(), output_len, ctx.allocator());
822
823        for &(chunk_idx, local_start, run) in &runs {
824            flattener.push(
825                array
826                    .chunk(chunk_idx)
827                    .slice(local_start..local_start + run)?,
828                ctx,
829            )?;
830        }
831
832        return flattener.finish(array.dtype(), ctx).map(Some);
833    }
834
835    // Out-of-order sub-pieces: flatten the per-chunk gathers, then take the sub-piece runs from
836    // the flattened result in output order.
837    let mut bases = Vec::with_capacity(plans.len());
838    let mut running = 0usize;
839    let mut flattener = ChunkFlattener::new(array.dtype(), output_len, ctx.allocator());
840    for (chunk_idx, plan) in plans {
841        bases.push(running);
842        running += plan.total;
843        flattener.push(gather_chunk(array.chunk(chunk_idx), plan)?, ctx)?;
844    }
845    let flat = flattener.finish(array.dtype(), ctx)?;
846
847    let mut reorder_starts = Vec::with_capacity(sub_pieces.len());
848    let mut reorder_lengths = Vec::with_capacity(sub_pieces.len());
849    for &(plan_idx, offset, run) in &sub_pieces {
850        reorder_starts.push((bases[plan_idx] + offset) as u64);
851        reorder_lengths.push(run as u64);
852    }
853    flat.take(contiguous_runs(reorder_starts, reorder_lengths, output_len))
854        .map(Some)
855}
856
857/// Tells if the runs are long and read a small part of each chunk.
858///
859/// Then a slice of each run reads less than the take of the runs of each chunk, also when the
860/// slice does its work at execution. In the `alp_fsl_take` bench, which has patches, a take of
861/// rows of 768 elements is up to 7 times faster this way, and a take of rows of 64 elements is
862/// 20% slower.
863fn sparse_long_runs(
864    array: ArrayView<'_, Chunked>,
865    plans: &[(usize, ChunkGather)],
866    num_runs: usize,
867    output_len: usize,
868) -> bool {
869    output_len >= num_runs * MIN_AVERAGE_EXECUTED_RUN
870        && plans.iter().all(|(chunk_idx, plan)| {
871            plan.total.saturating_mul(SPARSE_CHUNK_RATIO) <= array.chunk(*chunk_idx).len()
872        })
873}
874
875/// Tells if a slice of each chunk that `runs` read becomes an encoded array with no execution.
876///
877/// Such a slice decodes only its rows when it appends to a builder. A slice that does not
878/// reduce, such as a slice of an array with patches, does its work for each run, and a take of
879/// the runs of each chunk does it once for the chunk. The first run of each chunk is the test.
880fn slices_reduce(
881    array: ArrayView<'_, Chunked>,
882    runs: &[(usize, usize, usize)],
883    ctx: &mut ExecutionCtx,
884) -> VortexResult<bool> {
885    let mut tested = vec![false; array.nchunks()];
886
887    for &(chunk_idx, start, run) in runs {
888        if std::mem::replace(&mut tested[chunk_idx], true) {
889            continue;
890        }
891
892        let slice = array
893            .chunk(chunk_idx)
894            .slice(start..start + run)?
895            .optimize_ctx(ctx)?;
896
897        if slice.is::<Slice>() {
898            return Ok(false);
899        }
900    }
901
902    Ok(true)
903}
904
905/// Gathers a chunk's planned runs: a single run is a zero-copy slice, multiple runs become a
906/// chunk-local piecewise take.
907fn gather_chunk(chunk: &ArrayRef, plan: ChunkGather) -> VortexResult<ArrayRef> {
908    if let [start] = plan.starts.as_slice() {
909        let start = usize::try_from(*start)?;
910        return chunk.slice(start..start + plan.total);
911    }
912    chunk.take(contiguous_runs(plan.starts, plan.lengths, plan.total))
913}
914
915#[cfg(test)]
916mod tests {
917    use std::sync::LazyLock;
918
919    use vortex_buffer::Buffer;
920    use vortex_buffer::bitbuffer;
921    use vortex_buffer::buffer;
922    use vortex_error::VortexResult;
923    use vortex_session::VortexSession;
924
925    use crate::ArrayRef;
926    use crate::Canonical;
927    use crate::IntoArray;
928    use crate::VortexSessionExecute;
929    use crate::arrays::BoolArray;
930    use crate::arrays::ChunkedArray;
931    use crate::arrays::ConstantArray;
932    use crate::arrays::DictArray;
933    use crate::arrays::FixedSizeListArray;
934    use crate::arrays::PiecewiseSequenceArray;
935    use crate::arrays::PrimitiveArray;
936    use crate::arrays::StructArray;
937    use crate::arrays::chunked::ChunkedArrayExt;
938    use crate::assert_arrays_eq;
939    use crate::compute::conformance::take::test_take_conformance;
940    use crate::dtype::DType;
941    use crate::dtype::FieldNames;
942    use crate::dtype::Nullability;
943    use crate::dtype::PType;
944    use crate::scalar::Scalar;
945    use crate::validity::Validity;
946
947    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
948
949    fn chunked_i32() -> VortexResult<ChunkedArray> {
950        ChunkedArray::try_new(
951            vec![
952                buffer![0i32, 1, 2, 3, 4].into_array(),
953                buffer![5i32, 6, 7, 8, 9].into_array(),
954                buffer![10i32, 11, 12, 13, 14].into_array(),
955            ],
956            DType::Primitive(PType::I32, Nullability::NonNullable),
957        )
958    }
959
960    fn contiguous_pieces(starts: &[u64], lengths: &[u64]) -> VortexResult<ArrayRef> {
961        let len = usize::try_from(lengths.iter().sum::<u64>())?;
962        Ok(PiecewiseSequenceArray::try_new(
963            starts.iter().copied().collect::<Buffer<u64>>().into_array(),
964            lengths
965                .iter()
966                .copied()
967                .collect::<Buffer<u64>>()
968                .into_array(),
969            ConstantArray::new(1u64, starts.len()).into_array(),
970            len,
971        )?
972        .into_array())
973    }
974
975    #[test]
976    fn test_take_piecewise_monotonic_spanning_chunks() -> VortexResult<()> {
977        let mut ctx = SESSION.create_execution_ctx();
978        let arr = chunked_i32()?;
979
980        // The second piece crosses the first chunk boundary, the third spans the last two chunks.
981        let indices = contiguous_pieces(&[1, 4, 9], &[3, 4, 6])?;
982        let result = arr.take(indices)?;
983
984        assert_arrays_eq!(
985            result,
986            PrimitiveArray::from_iter([1i32, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13, 14]),
987            &mut ctx
988        );
989        Ok(())
990    }
991
992    #[test]
993    fn test_take_piecewise_interleaved() -> VortexResult<()> {
994        let mut ctx = SESSION.create_execution_ctx();
995        let arr = chunked_i32()?;
996
997        // Pieces visit chunks out of order, forcing the reorder take.
998        let indices = contiguous_pieces(&[12, 2, 7, 0], &[3, 2, 3, 1])?;
999        let result = arr.take(indices)?;
1000
1001        assert_arrays_eq!(
1002            result,
1003            PrimitiveArray::from_iter([12i32, 13, 14, 2, 3, 7, 8, 9, 0]),
1004            &mut ctx
1005        );
1006        Ok(())
1007    }
1008
1009    /// Long runs out of chunk order append to the result directly in output order.
1010    #[test]
1011    fn test_take_piecewise_interleaved_long_runs() -> VortexResult<()> {
1012        let mut ctx = SESSION.create_execution_ctx();
1013
1014        let chunks = (0..4)
1015            .map(|chunk| {
1016                (chunk * 512..(chunk + 1) * 512)
1017                    .collect::<Buffer<i32>>()
1018                    .into_array()
1019            })
1020            .collect::<Vec<_>>();
1021        let arr = ChunkedArray::try_new(
1022            chunks,
1023            DType::Primitive(PType::I32, Nullability::NonNullable),
1024        )?;
1025
1026        // The runs visit the chunks out of order. One run crosses a chunk boundary, and two
1027        // runs in the first chunk are in reverse order.
1028        let starts = [1600u64, 300, 900, 0, 1200];
1029        let lengths = [300u64, 200, 400, 200, 250];
1030        let result = arr.take(contiguous_pieces(&starts, &lengths)?)?;
1031
1032        let expected = starts.iter().zip(&lengths).flat_map(|(&start, &length)| {
1033            (start..start + length).map(|row| i32::try_from(row).unwrap_or(i32::MAX))
1034        });
1035
1036        assert_arrays_eq!(result, PrimitiveArray::from_iter(expected), &mut ctx);
1037        Ok(())
1038    }
1039
1040    /// Long runs out of chunk order keep the nulls of each row.
1041    #[test]
1042    fn test_take_piecewise_interleaved_long_runs_nullable() -> VortexResult<()> {
1043        let mut ctx = SESSION.create_execution_ctx();
1044
1045        let rows = |range: std::ops::Range<i32>| {
1046            PrimitiveArray::from_option_iter(range.map(|row| (row % 5 != 2).then_some(row)))
1047                .into_array()
1048        };
1049        let arr = ChunkedArray::try_new(
1050            vec![rows(0..512), rows(512..1024), rows(1024..1536)],
1051            DType::Primitive(PType::I32, Nullability::Nullable),
1052        )?;
1053
1054        let starts = [1100u64, 0, 700, 300];
1055        let lengths = [400u64, 150, 300, 200];
1056        let result = arr.take(contiguous_pieces(&starts, &lengths)?)?;
1057
1058        let expected = starts.iter().zip(&lengths).flat_map(|(&start, &length)| {
1059            (start..start + length).map(|row| {
1060                let row = i32::try_from(row).unwrap_or(i32::MAX);
1061                (row % 5 != 2).then_some(row)
1062            })
1063        });
1064
1065        assert_arrays_eq!(result, PrimitiveArray::from_option_iter(expected), &mut ctx);
1066        Ok(())
1067    }
1068
1069    #[test]
1070    fn test_take_piecewise_whole_array() -> VortexResult<()> {
1071        let mut ctx = SESSION.create_execution_ctx();
1072        let arr = chunked_i32()?;
1073
1074        let indices = contiguous_pieces(&[0], &[15])?;
1075        let result = arr.take(indices)?;
1076
1077        assert_arrays_eq!(result, PrimitiveArray::from_iter(0i32..15), &mut ctx);
1078        Ok(())
1079    }
1080
1081    #[test]
1082    fn test_take_piecewise_across_empty_chunk() -> VortexResult<()> {
1083        let mut ctx = SESSION.create_execution_ctx();
1084        let arr = ChunkedArray::try_new(
1085            vec![
1086                buffer![0i32, 1, 2, 3, 4].into_array(),
1087                PrimitiveArray::empty::<i32>(Nullability::NonNullable).into_array(),
1088                buffer![5i32, 6, 7, 8, 9].into_array(),
1089            ],
1090            DType::Primitive(PType::I32, Nullability::NonNullable),
1091        )?;
1092
1093        let indices = contiguous_pieces(&[3], &[4])?;
1094        let result = arr.take(indices)?;
1095
1096        assert_arrays_eq!(result, PrimitiveArray::from_iter([3i32, 4, 5, 6]), &mut ctx);
1097        Ok(())
1098    }
1099
1100    #[test]
1101    fn test_take_piecewise_adjacent_pieces_merge() -> VortexResult<()> {
1102        let mut ctx = SESSION.create_execution_ctx();
1103        let arr = chunked_i32()?;
1104
1105        // The first two pieces are contiguous within one chunk, so they merge into a single run
1106        // that gathers as a zero-copy slice.
1107        let indices = contiguous_pieces(&[0, 2, 7], &[2, 2, 2])?;
1108        let result = arr.take(indices)?;
1109
1110        assert_arrays_eq!(
1111            result,
1112            PrimitiveArray::from_iter([0i32, 1, 2, 3, 7, 8]),
1113            &mut ctx
1114        );
1115        Ok(())
1116    }
1117
1118    #[test]
1119    fn test_take_piecewise_same_chunk_out_of_order() -> VortexResult<()> {
1120        let mut ctx = SESSION.create_execution_ctx();
1121        let arr = chunked_i32()?;
1122
1123        // Non-contiguous pieces in the same chunk must stay separate runs in piece order.
1124        let indices = contiguous_pieces(&[2, 0], &[2, 2])?;
1125        let result = arr.take(indices)?;
1126
1127        assert_arrays_eq!(result, PrimitiveArray::from_iter([2i32, 3, 0, 1]), &mut ctx);
1128        Ok(())
1129    }
1130
1131    #[test]
1132    fn test_take_piecewise_zero_length_pieces() -> VortexResult<()> {
1133        let mut ctx = SESSION.create_execution_ctx();
1134        let arr = chunked_i32()?;
1135
1136        let indices = contiguous_pieces(&[5, 0, 2], &[0, 4, 0])?;
1137        let result = arr.take(indices)?;
1138
1139        assert_arrays_eq!(result, PrimitiveArray::from_iter([0i32, 1, 2, 3]), &mut ctx);
1140        Ok(())
1141    }
1142
1143    #[test]
1144    fn test_take_piecewise_out_of_bounds() -> VortexResult<()> {
1145        let mut ctx = SESSION.create_execution_ctx();
1146        let arr = chunked_i32()?;
1147
1148        let indices = contiguous_pieces(&[12], &[5])?;
1149        let result = arr
1150            .take(indices)
1151            .and_then(|taken| taken.execute::<Canonical>(&mut ctx));
1152
1153        assert!(result.is_err());
1154        Ok(())
1155    }
1156
1157    #[test]
1158    fn test_take_piecewise_non_unit_multiplier() -> VortexResult<()> {
1159        let mut ctx = SESSION.create_execution_ctx();
1160        let arr = chunked_i32()?;
1161
1162        // Multiplier 2 falls back to the generic path but must stay correct.
1163        let indices = PiecewiseSequenceArray::try_new(
1164            buffer![0u64, 1].into_array(),
1165            buffer![5u64, 3].into_array(),
1166            buffer![2u64, 4].into_array(),
1167            8,
1168        )?
1169        .into_array();
1170        let result = arr.take(indices)?;
1171
1172        assert_arrays_eq!(
1173            result,
1174            PrimitiveArray::from_iter([0i32, 2, 4, 6, 8, 1, 5, 9]),
1175            &mut ctx
1176        );
1177        Ok(())
1178    }
1179
1180    #[test]
1181    fn test_take_piecewise_nullable_values() -> VortexResult<()> {
1182        let mut ctx = SESSION.create_execution_ctx();
1183        let arr = ChunkedArray::try_new(
1184            vec![
1185                PrimitiveArray::from_option_iter([Some(0i32), None, Some(2)]).into_array(),
1186                PrimitiveArray::from_option_iter([None, Some(4i32), Some(5)]).into_array(),
1187            ],
1188            DType::Primitive(PType::I32, Nullability::Nullable),
1189        )?;
1190
1191        let indices = contiguous_pieces(&[4, 1], &[2, 3])?;
1192        let result = arr.take(indices)?;
1193
1194        assert_arrays_eq!(
1195            result,
1196            PrimitiveArray::from_option_iter([Some(4i32), Some(5), None, Some(2), None]),
1197            &mut ctx
1198        );
1199        Ok(())
1200    }
1201
1202    #[test]
1203    fn test_take_fsl_over_chunked_elements() -> VortexResult<()> {
1204        let mut ctx = SESSION.create_execution_ctx();
1205        // Chunk boundaries at 8 and 13 do not line up with the list size of 3.
1206        let elements = ChunkedArray::try_new(
1207            vec![
1208                PrimitiveArray::from_iter(0i32..8).into_array(),
1209                PrimitiveArray::from_iter(8i32..13).into_array(),
1210                PrimitiveArray::from_iter(13i32..18).into_array(),
1211            ],
1212            DType::Primitive(PType::I32, Nullability::NonNullable),
1213        )?
1214        .into_array();
1215        let fsl = FixedSizeListArray::try_new(elements, 3, Validity::NonNullable, 6)?;
1216
1217        let indices = buffer![4u64, 0, 2, 5, 1, 4].into_array();
1218        let result = fsl.take(indices)?;
1219        let expected = FixedSizeListArray::try_new(
1220            PrimitiveArray::from_iter([
1221                12i32, 13, 14, 0, 1, 2, 6, 7, 8, 15, 16, 17, 3, 4, 5, 12, 13, 14,
1222            ])
1223            .into_array(),
1224            3,
1225            Validity::NonNullable,
1226            6,
1227        )?;
1228
1229        assert_arrays_eq!(result, expected, &mut ctx);
1230        Ok(())
1231    }
1232
1233    #[test]
1234    fn test_take_fsl_over_chunked_elements_conformance() -> VortexResult<()> {
1235        let elements = ChunkedArray::try_new(
1236            vec![
1237                PrimitiveArray::from_iter(0i32..8).into_array(),
1238                PrimitiveArray::from_iter(8i32..13).into_array(),
1239                PrimitiveArray::from_iter(13i32..18).into_array(),
1240            ],
1241            DType::Primitive(PType::I32, Nullability::NonNullable),
1242        )?
1243        .into_array();
1244        let fsl = FixedSizeListArray::try_new(elements, 3, Validity::NonNullable, 6)?;
1245        test_take_conformance(&fsl.into_array(), &mut SESSION.create_execution_ctx());
1246        Ok(())
1247    }
1248
1249    #[test]
1250    fn test_take_chunked_fsl() -> VortexResult<()> {
1251        let mut ctx = SESSION.create_execution_ctx();
1252        let c0 = FixedSizeListArray::try_new(
1253            PrimitiveArray::from_iter(0i32..6).into_array(),
1254            2,
1255            Validity::NonNullable,
1256            3,
1257        )?;
1258        let c1 = FixedSizeListArray::try_new(
1259            PrimitiveArray::from_iter(6i32..10).into_array(),
1260            2,
1261            Validity::NonNullable,
1262            2,
1263        )?;
1264        let dtype = c0.dtype().clone();
1265        let arr = ChunkedArray::try_new(vec![c0.into_array(), c1.into_array()], dtype)?;
1266
1267        let indices = buffer![4u64, 0, 3, 3, 1].into_array();
1268        let result = arr.take(indices)?;
1269        let expected = FixedSizeListArray::try_new(
1270            PrimitiveArray::from_iter([8i32, 9, 0, 1, 6, 7, 6, 7, 2, 3]).into_array(),
1271            2,
1272            Validity::NonNullable,
1273            5,
1274        )?;
1275
1276        assert_arrays_eq!(result, expected, &mut ctx);
1277        Ok(())
1278    }
1279
1280    #[test]
1281    fn test_take_chunked_fsl_nullable() -> VortexResult<()> {
1282        let mut ctx = SESSION.create_execution_ctx();
1283        let c0 = FixedSizeListArray::try_new(
1284            PrimitiveArray::from_iter(0i32..6).into_array(),
1285            2,
1286            Validity::Array(bitbuffer![1 0 1].into_array()),
1287            3,
1288        )?;
1289        let c1 = FixedSizeListArray::try_new(
1290            PrimitiveArray::from_iter(6i32..10).into_array(),
1291            2,
1292            Validity::AllValid,
1293            2,
1294        )?;
1295        let dtype = c0.dtype().clone();
1296        let arr = ChunkedArray::try_new(vec![c0.into_array(), c1.into_array()], dtype)?;
1297
1298        let indices =
1299            PrimitiveArray::from_option_iter([Some(4u64), None, Some(0), Some(1)]).into_array();
1300        let result = arr.take(indices)?;
1301        let expected = FixedSizeListArray::try_new(
1302            PrimitiveArray::from_iter([8i32, 9, 0, 0, 0, 1, 0, 0]).into_array(),
1303            2,
1304            Validity::Array(bitbuffer![1 0 1 0].into_array()),
1305            4,
1306        )?;
1307
1308        assert_arrays_eq!(result, expected, &mut ctx);
1309        Ok(())
1310    }
1311
1312    #[test]
1313    fn test_take_chunked_fsl_non_fsl_chunk() -> VortexResult<()> {
1314        let mut ctx = SESSION.create_execution_ctx();
1315        let c0 = FixedSizeListArray::try_new(
1316            PrimitiveArray::from_iter(0i32..6).into_array(),
1317            2,
1318            Validity::NonNullable,
1319            3,
1320        )?;
1321        let c1 = FixedSizeListArray::try_new(
1322            PrimitiveArray::from_iter(6i32..10).into_array(),
1323            2,
1324            Validity::NonNullable,
1325            2,
1326        )?;
1327        let dtype = c0.dtype().clone();
1328        // Wrap one chunk in a nested chunked array so it is not FSL-encoded; the dtype-based
1329        // swizzle must still handle it.
1330        let nested = ChunkedArray::try_new(vec![c1.into_array()], dtype.clone())?;
1331        let arr = ChunkedArray::try_new(vec![c0.into_array(), nested.into_array()], dtype)?;
1332
1333        let indices = buffer![4u64, 0, 3, 1].into_array();
1334        let result = arr.take(indices)?;
1335        let expected = FixedSizeListArray::try_new(
1336            PrimitiveArray::from_iter([8i32, 9, 0, 1, 6, 7, 2, 3]).into_array(),
1337            2,
1338            Validity::NonNullable,
1339            4,
1340        )?;
1341
1342        assert_arrays_eq!(result, expected, &mut ctx);
1343        Ok(())
1344    }
1345
1346    #[test]
1347    fn test_take_chunked_fsl_constant_chunk() -> VortexResult<()> {
1348        let mut ctx = SESSION.create_execution_ctx();
1349        let c0 = FixedSizeListArray::try_new(
1350            PrimitiveArray::from_iter(0i32..6).into_array(),
1351            2,
1352            Validity::AllValid,
1353            3,
1354        )?;
1355        let dtype = c0.dtype().clone();
1356        // A constant chunk is only logically FSL; the swizzle canonicalizes it in place.
1357        let c1 = ConstantArray::new(Scalar::null(dtype.clone()), 2).into_array();
1358        let arr = ChunkedArray::try_new(vec![c0.into_array(), c1], dtype)?;
1359
1360        let indices = buffer![4u64, 0, 3, 1].into_array();
1361        let result = arr.take(indices)?;
1362        let expected = FixedSizeListArray::try_new(
1363            PrimitiveArray::from_iter([0i32, 0, 0, 1, 0, 0, 2, 3]).into_array(),
1364            2,
1365            Validity::Array(bitbuffer![0 1 0 1].into_array()),
1366            4,
1367        )?;
1368
1369        assert_arrays_eq!(result, expected, &mut ctx);
1370        Ok(())
1371    }
1372
1373    #[test]
1374    fn test_take_piecewise_chunked_fsl() -> VortexResult<()> {
1375        let mut ctx = SESSION.create_execution_ctx();
1376        let c0 = FixedSizeListArray::try_new(
1377            PrimitiveArray::from_iter(0i32..6).into_array(),
1378            2,
1379            Validity::NonNullable,
1380            3,
1381        )?;
1382        let c1 = FixedSizeListArray::try_new(
1383            PrimitiveArray::from_iter(6i32..10).into_array(),
1384            2,
1385            Validity::NonNullable,
1386            2,
1387        )?;
1388        let dtype = c0.dtype().clone();
1389        let arr = ChunkedArray::try_new(vec![c0.into_array(), c1.into_array()], dtype)?;
1390        let reference = FixedSizeListArray::try_new(
1391            PrimitiveArray::from_iter(0i32..10).into_array(),
1392            2,
1393            Validity::NonNullable,
1394            5,
1395        )?;
1396
1397        // A monotonic run crossing the chunk boundary.
1398        let indices = contiguous_pieces(&[1], &[3])?;
1399        let result = arr.take(indices.clone())?;
1400        assert_arrays_eq!(&result, reference.take(indices)?, &mut ctx);
1401        let expected = FixedSizeListArray::try_new(
1402            PrimitiveArray::from_iter([2i32, 3, 4, 5, 6, 7]).into_array(),
1403            2,
1404            Validity::NonNullable,
1405            3,
1406        )?;
1407        assert_arrays_eq!(result, expected, &mut ctx);
1408
1409        // Out-of-order pieces forcing the reorder take.
1410        let indices = contiguous_pieces(&[3, 0], &[2, 2])?;
1411        let result = arr.take(indices.clone())?;
1412        assert_arrays_eq!(&result, reference.take(indices)?, &mut ctx);
1413        let expected = FixedSizeListArray::try_new(
1414            PrimitiveArray::from_iter([6i32, 7, 8, 9, 0, 1, 2, 3]).into_array(),
1415            2,
1416            Validity::NonNullable,
1417            4,
1418        )?;
1419        assert_arrays_eq!(result, expected, &mut ctx);
1420        Ok(())
1421    }
1422
1423    #[test]
1424    fn test_take_chunked_struct_nested_flatten() -> VortexResult<()> {
1425        let mut ctx = SESSION.create_execution_ctx();
1426        let s0 = StructArray::try_new(
1427            ["a"].into(),
1428            vec![buffer![0i32, 1, 2].into_array()],
1429            3,
1430            Validity::NonNullable,
1431        )?;
1432        let s1 = StructArray::try_new(
1433            ["a"].into(),
1434            vec![buffer![3i32, 4].into_array()],
1435            2,
1436            Validity::NonNullable,
1437        )?;
1438        let dtype = s0.dtype().clone();
1439        let arr = ChunkedArray::try_new(vec![s0.into_array(), s1.into_array()], dtype)?;
1440
1441        let result = arr.take(buffer![4u64, 0, 2, 4].into_array())?;
1442        let expected = StructArray::try_new(
1443            ["a"].into(),
1444            vec![buffer![4i32, 0, 2, 4].into_array()],
1445            4,
1446            Validity::NonNullable,
1447        )?;
1448
1449        assert_arrays_eq!(result, expected, &mut ctx);
1450        Ok(())
1451    }
1452
1453    /// A nullable struct of a fixed-size list and a primitive, in chunks of 3, 2 and 4 rows.
1454    fn chunked_struct_of_fsl() -> VortexResult<(ChunkedArray, StructArray)> {
1455        let lengths = [3usize, 2, 4];
1456        let mut chunks = Vec::new();
1457        let mut start = 0usize;
1458
1459        for length in lengths {
1460            let rows = start..start + length;
1461            let tokens = FixedSizeListArray::try_new(
1462                PrimitiveArray::from_iter((rows.start * 2..rows.end * 2).map(|v| v as u64))
1463                    .into_array(),
1464                2,
1465                Validity::NonNullable,
1466                length,
1467            )?;
1468            let ids = PrimitiveArray::from_iter(rows.clone().map(|v| v as u64));
1469            let validity = Validity::from_iter(rows.map(|row| row % 4 != 1));
1470            chunks.push(
1471                StructArray::try_new(
1472                    ["tokens", "id"].into(),
1473                    vec![tokens.into_array(), ids.into_array()],
1474                    length,
1475                    validity,
1476                )?
1477                .into_array(),
1478            );
1479            start += length;
1480        }
1481
1482        let dtype = chunks[0].dtype().clone();
1483        let chunked = ChunkedArray::try_new(chunks, dtype)?;
1484
1485        let tokens = FixedSizeListArray::try_new(
1486            PrimitiveArray::from_iter((0..start * 2).map(|v| v as u64)).into_array(),
1487            2,
1488            Validity::NonNullable,
1489            start,
1490        )?;
1491        let flat = StructArray::try_new(
1492            ["tokens", "id"].into(),
1493            vec![
1494                tokens.into_array(),
1495                PrimitiveArray::from_iter((0..start).map(|v| v as u64)).into_array(),
1496            ],
1497            start,
1498            Validity::from_iter((0..start).map(|row| row % 4 != 1)),
1499        )?;
1500        Ok((chunked, flat))
1501    }
1502
1503    #[test]
1504    fn test_take_chunked_struct_of_fsl() -> VortexResult<()> {
1505        let mut ctx = SESSION.create_execution_ctx();
1506        let (chunked, flat) = chunked_struct_of_fsl()?;
1507
1508        for indices in [
1509            buffer![0u64, 2, 3, 5, 8].into_array(),
1510            buffer![8u64, 1, 4, 4, 0, 6].into_array(),
1511            buffer![7u64].into_array(),
1512            buffer![6u64, 0, 7, 0].into_array(),
1513            Buffer::<u64>::empty().into_array(),
1514            PrimitiveArray::from_option_iter([Some(5u64), None, Some(2)]).into_array(),
1515        ] {
1516            let result = chunked.clone().into_array().take(indices.clone())?;
1517            let expected = flat.clone().into_array().take(indices)?;
1518            assert_arrays_eq!(result, expected, &mut ctx);
1519        }
1520        Ok(())
1521    }
1522
1523    /// Takes that touch some of the chunks, around an empty chunk, read only those chunks and keep
1524    /// the order and the duplicates of the indices.
1525    #[test]
1526    fn test_take_chunked_fsl_touched_chunks() -> VortexResult<()> {
1527        let mut ctx = SESSION.create_execution_ctx();
1528        let lengths = [2usize, 0, 3, 1, 2];
1529        let mut chunks = Vec::new();
1530        let mut start = 0u64;
1531
1532        for length in lengths {
1533            let end = start + length as u64;
1534            chunks.push(
1535                FixedSizeListArray::try_new(
1536                    PrimitiveArray::from_iter(start * 2..end * 2).into_array(),
1537                    2,
1538                    Validity::NonNullable,
1539                    length,
1540                )?
1541                .into_array(),
1542            );
1543            start = end;
1544        }
1545
1546        let dtype = chunks[0].dtype().clone();
1547        let chunked = ChunkedArray::try_new(chunks, dtype)?.into_array();
1548        let flat = FixedSizeListArray::try_new(
1549            PrimitiveArray::from_iter(0..start * 2).into_array(),
1550            2,
1551            Validity::NonNullable,
1552            usize::try_from(start)?,
1553        )?
1554        .into_array();
1555
1556        for indices in [
1557            buffer![7u64, 2, 2, 6].into_array(),
1558            buffer![4u64, 3].into_array(),
1559            buffer![1u64].into_array(),
1560        ] {
1561            let result = chunked.take(indices.clone())?;
1562            assert_arrays_eq!(result, flat.take(indices)?, &mut ctx);
1563        }
1564
1565        let out_of_bounds = chunked.take(buffer![1u64, 8].into_array())?;
1566        assert!(out_of_bounds.execute::<Canonical>(&mut ctx).is_err());
1567        Ok(())
1568    }
1569
1570    #[test]
1571    fn test_touched_chunks_piecewise_without_expanding() -> VortexResult<()> {
1572        let mut ctx = SESSION.create_execution_ctx();
1573        let lengths = [2usize, 0, 3, 1, 2];
1574        let mut chunks = Vec::new();
1575        let mut start = 0u64;
1576
1577        for length in lengths {
1578            let end = start + length as u64;
1579            chunks.push(
1580                FixedSizeListArray::try_new(
1581                    PrimitiveArray::from_iter(start * 2..end * 2).into_array(),
1582                    2,
1583                    Validity::NonNullable,
1584                    length,
1585                )?
1586                .into_array(),
1587            );
1588            start = end;
1589        }
1590
1591        let dtype = chunks[0].dtype().clone();
1592        let chunked = ChunkedArray::try_new(chunks, dtype)?;
1593        let flat = FixedSizeListArray::try_new(
1594            PrimitiveArray::from_iter(0..start * 2).into_array(),
1595            2,
1596            Validity::NonNullable,
1597            usize::try_from(start)?,
1598        )?
1599        .into_array();
1600
1601        for (indices, expected_chunks) in [
1602            (contiguous_pieces(&[1], &[3])?, 2usize),
1603            (contiguous_pieces(&[6, 1, 6], &[2, 2, 1])?, 3usize),
1604            (contiguous_pieces(&[2], &[2])?, 1usize),
1605        ] {
1606            let (touched, remapped) = super::touched_chunks(chunked.as_view(), &indices, &mut ctx)?
1607                .expect("sparse piecewise indices should select a subset of chunks");
1608            assert_eq!(touched.len(), expected_chunks);
1609            assert!(remapped.is::<super::PiecewiseSequence>());
1610
1611            let result = chunked.clone().into_array().take(indices.clone())?;
1612            assert_arrays_eq!(result, flat.take(indices)?, &mut ctx);
1613        }
1614
1615        let out_of_bounds = contiguous_pieces(&[6], &[3])?;
1616        assert!(super::touched_chunks(chunked.as_view(), &out_of_bounds, &mut ctx).is_err());
1617        Ok(())
1618    }
1619
1620    #[test]
1621    fn test_take_chunked_struct_conformance() -> VortexResult<()> {
1622        let (chunked, _) = chunked_struct_of_fsl()?;
1623        test_take_conformance(&chunked.into_array(), &mut SESSION.create_execution_ctx());
1624        Ok(())
1625    }
1626
1627    #[test]
1628    fn test_take_chunked_struct_constant_chunk() -> VortexResult<()> {
1629        let mut ctx = SESSION.create_execution_ctx();
1630        let s0 = StructArray::try_new(
1631            ["a"].into(),
1632            vec![buffer![0i32, 1, 2].into_array()],
1633            3,
1634            Validity::NonNullable,
1635        )?;
1636        let dtype = s0.dtype().clone();
1637        // A constant chunk is only logically a struct, so the take does not swizzle the chunks.
1638        let s1 = ConstantArray::new(Scalar::struct_(dtype.clone(), vec![7i32.into()]), 2);
1639        let arr = ChunkedArray::try_new(vec![s0.into_array(), s1.into_array()], dtype)?;
1640
1641        let result = arr.take(buffer![4u64, 0, 3, 2].into_array())?;
1642        let expected = StructArray::try_new(
1643            ["a"].into(),
1644            vec![buffer![7i32, 0, 7, 2].into_array()],
1645            4,
1646            Validity::NonNullable,
1647        )?;
1648
1649        assert_arrays_eq!(result, expected, &mut ctx);
1650        Ok(())
1651    }
1652
1653    /// The take swizzles the struct chunks that the indices touch, also when an untouched chunk is
1654    /// not a struct. When the indices touch the constant chunk, the take does not swizzle.
1655    #[test]
1656    fn test_take_chunked_struct_of_fsl_constant_chunk() -> VortexResult<()> {
1657        let mut ctx = SESSION.create_execution_ctx();
1658
1659        let struct_of_fsl = |start: i32, length: usize| -> VortexResult<ArrayRef> {
1660            let end = start + i32::try_from(length)?;
1661            let tokens = FixedSizeListArray::try_new(
1662                PrimitiveArray::from_iter(start * 2..end * 2).into_array(),
1663                2,
1664                Validity::NonNullable,
1665                length,
1666            )?;
1667
1668            Ok(StructArray::try_new(
1669                ["tokens"].into(),
1670                vec![tokens.into_array()],
1671                length,
1672                Validity::NonNullable,
1673            )?
1674            .into_array())
1675        };
1676
1677        let s0 = struct_of_fsl(0, 2)?;
1678        let s2 = struct_of_fsl(4, 2)?;
1679        let dtype = s0.dtype().clone();
1680
1681        let scalar = struct_of_fsl(50, 1)?.execute_scalar(0, &mut ctx)?;
1682        let s1 = ConstantArray::new(scalar, 2).into_array();
1683
1684        let chunked = ChunkedArray::try_new(vec![s0, s1, s2], dtype)?.into_array();
1685        let flat = chunked
1686            .clone()
1687            .execute::<StructArray>(&mut ctx)?
1688            .into_array();
1689
1690        for indices in [
1691            buffer![5u64, 0, 4, 1].into_array(),
1692            buffer![3u64, 0, 5, 2].into_array(),
1693        ] {
1694            let result = chunked.take(indices.clone())?;
1695            assert_arrays_eq!(result, flat.take(indices)?, &mut ctx);
1696        }
1697
1698        Ok(())
1699    }
1700
1701    /// A take from struct chunks with dictionary-encoded fixed-size-list fields does not swizzle
1702    /// them. The swizzle would decode every dictionary code of the chunks that the take touches.
1703    #[test]
1704    fn test_take_chunked_struct_of_dict_fsl() -> VortexResult<()> {
1705        let mut ctx = SESSION.create_execution_ctx();
1706
1707        let struct_of_dict_fsl = |values: Vec<u64>, codes: Vec<u32>| -> VortexResult<ArrayRef> {
1708            let values_len = values.len() / 2;
1709            let values = FixedSizeListArray::try_new(
1710                PrimitiveArray::from_iter(values).into_array(),
1711                2,
1712                Validity::NonNullable,
1713                values_len,
1714            )?;
1715
1716            let length = codes.len();
1717            let tokens = DictArray::try_new(
1718                PrimitiveArray::from_iter(codes).into_array(),
1719                values.into_array(),
1720            )?;
1721
1722            Ok(StructArray::try_new(
1723                ["tokens"].into(),
1724                vec![tokens.into_array()],
1725                length,
1726                Validity::NonNullable,
1727            )?
1728            .into_array())
1729        };
1730
1731        let s0 = struct_of_dict_fsl(vec![0, 1, 2, 3], vec![1, 0, 1, 1])?;
1732        let s1 = struct_of_dict_fsl(vec![10, 11, 12, 13, 14, 15], vec![2, 0, 1])?;
1733        let s2 = struct_of_dict_fsl(vec![20, 21], vec![0, 0])?;
1734        let dtype = s0.dtype().clone();
1735        let chunked = ChunkedArray::try_new(vec![s0, s1, s2], dtype)?;
1736
1737        let tokens = FixedSizeListArray::try_new(
1738            PrimitiveArray::from_iter([
1739                2u64, 3, 0, 1, 2, 3, 2, 3, 14, 15, 10, 11, 12, 13, 20, 21, 20, 21,
1740            ])
1741            .into_array(),
1742            2,
1743            Validity::NonNullable,
1744            9,
1745        )?;
1746        let flat = StructArray::try_new(
1747            ["tokens"].into(),
1748            vec![tokens.into_array()],
1749            9,
1750            Validity::NonNullable,
1751        )?
1752        .into_array();
1753
1754        for indices in [
1755            buffer![0u64, 4].into_array(),
1756            buffer![6u64, 1, 5].into_array(),
1757            buffer![8u64, 0, 4].into_array(),
1758        ] {
1759            let swizzled = super::take_chunked_struct(chunked.as_view(), &indices, &mut ctx)?;
1760            assert!(swizzled.is_none());
1761
1762            let result = chunked.clone().into_array().take(indices.clone())?;
1763            assert_arrays_eq!(result, flat.take(indices)?, &mut ctx);
1764        }
1765
1766        Ok(())
1767    }
1768
1769    #[test]
1770    fn test_take_chunked_fsl_conformance() -> VortexResult<()> {
1771        let c0 = FixedSizeListArray::try_new(
1772            PrimitiveArray::from_iter(0i32..6).into_array(),
1773            2,
1774            Validity::NonNullable,
1775            3,
1776        )?;
1777        let c1 = FixedSizeListArray::try_new(
1778            PrimitiveArray::from_iter(6i32..10).into_array(),
1779            2,
1780            Validity::NonNullable,
1781            2,
1782        )?;
1783        let dtype = c0.dtype().clone();
1784        let arr = ChunkedArray::try_new(vec![c0.into_array(), c1.into_array()], dtype)?;
1785        test_take_conformance(&arr.into_array(), &mut SESSION.create_execution_ctx());
1786        Ok(())
1787    }
1788
1789    #[test]
1790    fn test_take() {
1791        let mut ctx = SESSION.create_execution_ctx();
1792        let a = buffer![1i32, 2, 3].into_array();
1793        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
1794            .unwrap();
1795        assert_eq!(arr.nchunks(), 3);
1796        assert_eq!(arr.len(), 9);
1797        let indices = buffer![0u64, 0, 6, 4].into_array();
1798
1799        let result = arr.take(indices).unwrap();
1800        assert_arrays_eq!(result, PrimitiveArray::from_iter([1i32, 1, 1, 2]), &mut ctx);
1801    }
1802
1803    #[test]
1804    fn test_take_nullable_values() {
1805        let mut ctx = SESSION.create_execution_ctx();
1806        let a = PrimitiveArray::new(buffer![1i32, 2, 3], Validity::AllValid).into_array();
1807        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
1808            .unwrap();
1809        assert_eq!(arr.nchunks(), 3);
1810        assert_eq!(arr.len(), 9);
1811        let indices = PrimitiveArray::new(buffer![0u64, 0, 6, 4], Validity::NonNullable);
1812
1813        let result = arr.take(indices.into_array()).unwrap();
1814        assert_arrays_eq!(
1815            result,
1816            PrimitiveArray::from_option_iter([1i32, 1, 1, 2].map(Some)),
1817            &mut ctx
1818        );
1819    }
1820
1821    #[test]
1822    fn test_take_nullable_indices() {
1823        let mut ctx = SESSION.create_execution_ctx();
1824        let a = buffer![1i32, 2, 3].into_array();
1825        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
1826            .unwrap();
1827        assert_eq!(arr.nchunks(), 3);
1828        assert_eq!(arr.len(), 9);
1829        let indices = PrimitiveArray::new(
1830            buffer![0u64, 0, 6, 4],
1831            Validity::Array(bitbuffer![1 0 0 1].into_array()),
1832        );
1833
1834        let result = arr.take(indices.into_array()).unwrap();
1835        assert_arrays_eq!(
1836            result,
1837            PrimitiveArray::from_option_iter([Some(1i32), None, None, Some(2)]),
1838            &mut ctx
1839        );
1840    }
1841
1842    #[test]
1843    fn test_take_nullable_struct() {
1844        let mut ctx = SESSION.create_execution_ctx();
1845        let struct_array =
1846            StructArray::try_new(FieldNames::default(), vec![], 100, Validity::NonNullable)
1847                .unwrap();
1848
1849        let arr = ChunkedArray::from_iter(vec![
1850            struct_array.clone().into_array(),
1851            struct_array.into_array(),
1852        ]);
1853
1854        let result = arr
1855            .take(PrimitiveArray::from_option_iter(vec![Some(0), None, Some(101)]).into_array())
1856            .unwrap();
1857
1858        let expect = StructArray::try_new(
1859            FieldNames::default(),
1860            vec![],
1861            3,
1862            Validity::Array(BoolArray::from_iter(vec![true, false, true]).into_array()),
1863        )
1864        .unwrap();
1865        assert_arrays_eq!(result, expect, &mut ctx);
1866    }
1867
1868    #[test]
1869    fn test_empty_take() {
1870        let mut ctx = SESSION.create_execution_ctx();
1871        let a = buffer![1i32, 2, 3].into_array();
1872        let arr = ChunkedArray::try_new(vec![a.clone(), a.clone(), a.clone()], a.dtype().clone())
1873            .unwrap();
1874        assert_eq!(arr.nchunks(), 3);
1875        assert_eq!(arr.len(), 9);
1876
1877        let indices = PrimitiveArray::empty::<u64>(Nullability::NonNullable);
1878        let result = arr.take(indices.into_array()).unwrap();
1879
1880        assert!(result.is_empty());
1881        assert_eq!(result.dtype(), arr.dtype());
1882        assert_arrays_eq!(
1883            result,
1884            PrimitiveArray::empty::<i32>(Nullability::NonNullable),
1885            &mut ctx
1886        );
1887    }
1888
1889    #[test]
1890    fn test_take_shuffled_indices() -> VortexResult<()> {
1891        let mut ctx = SESSION.create_execution_ctx();
1892        let c0 = buffer![0i32, 1, 2].into_array();
1893        let c1 = buffer![3i32, 4, 5].into_array();
1894        let c2 = buffer![6i32, 7, 8].into_array();
1895        let arr = ChunkedArray::try_new(
1896            vec![c0, c1, c2],
1897            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
1898                .dtype()
1899                .clone(),
1900        )?;
1901
1902        // Fully shuffled indices that cross every chunk boundary.
1903        let indices = buffer![8u64, 0, 5, 3, 2, 7, 1, 6, 4].into_array();
1904        let result = arr.take(indices)?;
1905
1906        assert_arrays_eq!(
1907            result,
1908            PrimitiveArray::from_iter([8i32, 0, 5, 3, 2, 7, 1, 6, 4]),
1909            &mut ctx
1910        );
1911        Ok(())
1912    }
1913
1914    #[test]
1915    fn test_take_shuffled_duplicates_with_empty_chunks() -> VortexResult<()> {
1916        let mut ctx = SESSION.create_execution_ctx();
1917        let empty = PrimitiveArray::empty::<i32>(Nullability::NonNullable).into_array();
1918        let arr = ChunkedArray::try_new(
1919            vec![
1920                empty.clone(),
1921                buffer![0i32, 1].into_array(),
1922                empty.clone(),
1923                buffer![2i32, 3].into_array(),
1924                empty,
1925            ],
1926            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
1927                .dtype()
1928                .clone(),
1929        )?;
1930
1931        let result = arr.take(buffer![3u64, 0, 2, 0, 3, 1, 2].into_array())?;
1932
1933        assert_arrays_eq!(
1934            result,
1935            PrimitiveArray::from_iter([3i32, 0, 2, 0, 3, 1, 2]),
1936            &mut ctx
1937        );
1938        Ok(())
1939    }
1940
1941    #[test]
1942    fn test_take_small_shuffled_fixed_size_lists() -> VortexResult<()> {
1943        let mut ctx = SESSION.create_execution_ctx();
1944        let first = FixedSizeListArray::new(
1945            buffer![0i32, 1, 2, 3].into_array(),
1946            2,
1947            Validity::NonNullable,
1948            2,
1949        )
1950        .into_array();
1951        let second = FixedSizeListArray::new(
1952            buffer![4i32, 5, 6, 7].into_array(),
1953            2,
1954            Validity::NonNullable,
1955            2,
1956        )
1957        .into_array();
1958        let dtype = first.dtype().clone();
1959        let array = ChunkedArray::try_new(vec![first, second], dtype)?;
1960
1961        let result = array.take(buffer![3u64, 0, 2, 1, 3].into_array())?;
1962        let expected = FixedSizeListArray::new(
1963            buffer![6i32, 7, 0, 1, 4, 5, 2, 3, 6, 7].into_array(),
1964            2,
1965            Validity::NonNullable,
1966            5,
1967        );
1968
1969        assert_arrays_eq!(result, expected, &mut ctx);
1970        Ok(())
1971    }
1972
1973    #[test]
1974    fn test_take_shuffled_large() -> VortexResult<()> {
1975        let mut ctx = SESSION.create_execution_ctx();
1976        let nchunks: i32 = 100;
1977        let chunk_len: i32 = 1_000;
1978        let total = nchunks * chunk_len;
1979
1980        let chunks: Vec<_> = (0..nchunks)
1981            .map(|c| {
1982                let start = c * chunk_len;
1983                PrimitiveArray::from_iter(start..start + chunk_len).into_array()
1984            })
1985            .collect();
1986        let dtype = chunks[0].dtype().clone();
1987        let arr = ChunkedArray::try_new(chunks, dtype)?;
1988
1989        // Fisher-Yates shuffle with a fixed seed for determinism.
1990        let mut indices: Vec<u64> = (0..u64::try_from(total)?).collect();
1991        let mut seed: u64 = 0xdeadbeef;
1992        for i in (1..indices.len()).rev() {
1993            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
1994            let j = (seed >> 33) as usize % (i + 1);
1995            indices.swap(i, j);
1996        }
1997
1998        let indices_arr = PrimitiveArray::new(Buffer::from(indices.clone()), Validity::NonNullable);
1999        let result = arr.take(indices_arr.into_array())?;
2000
2001        // Verify every element.
2002        let result = result.execute::<PrimitiveArray>(&mut ctx)?;
2003        assert_eq!(
2004            result.dtype(),
2005            &DType::Primitive(PType::I32, Nullability::NonNullable)
2006        );
2007        assert_eq!(result.len(), indices.len());
2008        let result_vals = result.as_slice::<i32>();
2009        for (pos, &idx) in indices.iter().enumerate() {
2010            assert_eq!(
2011                result_vals[pos],
2012                i32::try_from(idx)?,
2013                "mismatch at position {pos}"
2014            );
2015        }
2016        Ok(())
2017    }
2018
2019    #[test]
2020    fn test_take_null_indices() -> VortexResult<()> {
2021        let mut ctx = SESSION.create_execution_ctx();
2022        let c0 = buffer![10i32, 20, 30].into_array();
2023        let c1 = buffer![40i32, 50, 60].into_array();
2024        let arr = ChunkedArray::try_new(
2025            vec![c0, c1],
2026            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
2027                .dtype()
2028                .clone(),
2029        )?;
2030
2031        // Indices with nulls scattered across chunk boundaries.
2032        let indices =
2033            PrimitiveArray::from_option_iter([Some(5u64), None, Some(0), Some(3), None, Some(2)]);
2034        let result = arr.take(indices.into_array())?;
2035
2036        assert_arrays_eq!(
2037            result,
2038            PrimitiveArray::from_option_iter([
2039                Some(60i32),
2040                None,
2041                Some(10),
2042                Some(40),
2043                None,
2044                Some(30)
2045            ]),
2046            &mut ctx
2047        );
2048        Ok(())
2049    }
2050
2051    #[test]
2052    fn test_take_sorted_indices() -> VortexResult<()> {
2053        let mut ctx = SESSION.create_execution_ctx();
2054        let arr = chunked_i32()?;
2055
2056        // Strictly increasing indices spanning chunks hit the sorted fast path.
2057        let indices = buffer![1u64, 4, 5, 9, 10, 14].into_array();
2058        let result = arr.take(indices)?;
2059
2060        assert_arrays_eq!(
2061            result,
2062            PrimitiveArray::from_iter([1i32, 4, 5, 9, 10, 14]),
2063            &mut ctx
2064        );
2065        Ok(())
2066    }
2067
2068    #[test]
2069    fn test_take_out_of_bounds() -> VortexResult<()> {
2070        let mut ctx = SESSION.create_execution_ctx();
2071        let arr = chunked_i32()?;
2072
2073        // Sorted indices hit the fast path, unsorted the generic path; both must fail.
2074        for indices in [buffer![0u64, 100], buffer![100u64, 0]] {
2075            let result = arr
2076                .take(indices.into_array())
2077                .and_then(|taken| taken.execute::<Canonical>(&mut ctx));
2078            assert!(result.is_err(), "expected out-of-bounds error");
2079        }
2080        Ok(())
2081    }
2082
2083    #[test]
2084    fn test_take_all_null_indices() -> VortexResult<()> {
2085        let mut ctx = SESSION.create_execution_ctx();
2086        let arr = chunked_i32()?;
2087
2088        let indices = PrimitiveArray::from_option_iter([None::<u64>, None]).into_array();
2089        let result = arr.take(indices)?;
2090
2091        assert_arrays_eq!(
2092            result,
2093            PrimitiveArray::from_option_iter([None::<i32>, None]),
2094            &mut ctx
2095        );
2096        Ok(())
2097    }
2098
2099    #[test]
2100    fn test_take_chunked_conformance() {
2101        let a = buffer![1i32, 2, 3].into_array();
2102        let b = buffer![4i32, 5].into_array();
2103        let arr = ChunkedArray::try_new(
2104            vec![a, b],
2105            PrimitiveArray::empty::<i32>(Nullability::NonNullable)
2106                .dtype()
2107                .clone(),
2108        )
2109        .unwrap();
2110        test_take_conformance(&arr.into_array(), &mut SESSION.create_execution_ctx());
2111
2112        // Test with nullable chunked array
2113        let a = PrimitiveArray::from_option_iter([Some(1i32), None, Some(3)]);
2114        let b = PrimitiveArray::from_option_iter([Some(4i32), Some(5)]);
2115        let dtype = a.dtype().clone();
2116        let arr = ChunkedArray::try_new(vec![a.into_array(), b.into_array()], dtype).unwrap();
2117        test_take_conformance(&arr.into_array(), &mut SESSION.create_execution_ctx());
2118
2119        // Test with multiple identical chunks
2120        let chunk = buffer![10i32, 20, 30, 40, 50].into_array();
2121        let arr = ChunkedArray::try_new(
2122            vec![chunk.clone(), chunk.clone(), chunk.clone()],
2123            chunk.dtype().clone(),
2124        )
2125        .unwrap();
2126        test_take_conformance(&arr.into_array(), &mut SESSION.create_execution_ctx());
2127    }
2128}