Skip to main content

vortex_array/arrays/listview/
rebuild.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use num_traits::FromPrimitive;
5use vortex_buffer::BufferAllocatorRef;
6use vortex_buffer::BufferMut;
7use vortex_error::VortexExpect;
8use vortex_error::VortexResult;
9use vortex_error::vortex_bail;
10use vortex_error::vortex_err;
11use vortex_mask::Mask;
12
13use crate::Canonical;
14use crate::ExecutionCtx;
15use crate::IntoArray;
16use crate::arrays::ConstantArray;
17use crate::arrays::ListViewArray;
18use crate::arrays::PiecewiseSequenceArray;
19use crate::arrays::PrimitiveArray;
20use crate::arrays::list::drop_unreferenced_elements;
21use crate::arrays::list::null_runs_holding_elements;
22use crate::arrays::listview::ListViewArrayExt;
23use crate::arrays::listview::ListViewArraySlotsExt;
24use crate::arrays::primitive::PrimitiveArrayExt;
25use crate::builtins::ArrayBuiltins;
26use crate::dtype::IntegerPType;
27use crate::dtype::Nullability;
28use crate::dtype::PType;
29use crate::match_each_integer_ptype;
30use crate::match_each_unsigned_integer_ptype;
31use crate::optimizer::ArrayOptimizer;
32use crate::scalar::NumericOperator;
33use crate::scalar::Scalar;
34use crate::validity::Validity;
35
36/// The widened offset type used for a rebuilt, zero-copy-to-list array.
37///
38/// Offsets are widened to at least 32 bits (Arrow only permits 32/64-bit list offsets) while
39/// preserving signedness, since a signed result keeps the array zero-copyable to Arrow's
40/// `ListArray`.
41fn rebuilt_offset_ptype(offsets_ptype: PType) -> PType {
42    match offsets_ptype {
43        PType::U8 | PType::U16 | PType::U32 => PType::U32,
44        PType::U64 => PType::U64,
45        PType::I8 | PType::I16 | PType::I32 => PType::I32,
46        PType::I64 => PType::I64,
47        _ => unreachable!("invalid offsets PType"),
48    }
49}
50
51/// Density threshold to decide whether to rebuild a sparse `ListViewArray`.
52///
53/// A `ListViewArray` can accumulate unreferenced bytes in its `elements` buffer after
54/// metadata-only operations like `take` and `filter`. When density (referenced fraction of `elements`)
55/// falls below this threshold, the benefits of a rebuild may outweigh its cost.
56///
57/// This is a somewhat arbitrary rule-of-thumb and may be suboptimal depending on different use cases and
58/// list element dtypes.
59pub const DEFAULT_REBUILD_DENSITY_THRESHOLD: f32 = 0.1;
60
61/// Waste threshold to decide whether to trim a zero-copy-to-list `ListViewArray`.
62///
63/// A zero-copy-to-list array has no overlaps and no interior gaps, so its only unreferenced bytes
64/// are leading and trailing elements. Trimming those is much cheaper than a full rebuild (a lazy
65/// `elements` slice plus an `O(num_lists)` offset adjustment, with no element data copy), so we use
66/// a more aggressive threshold than [`DEFAULT_REBUILD_DENSITY_THRESHOLD`].
67///
68/// When the unreferenced (leading + trailing) fraction of `elements` exceeds this threshold, we trim.
69pub const DEFAULT_TRIM_ELEMENTS_THRESHOLD: f32 = 0.05;
70
71/// Modes for rebuilding a [`ListViewArray`].
72pub enum ListViewRebuildMode {
73    /// Removes all unused data and flattens out all list data, such that the array is zero-copyable
74    /// to a [`ListArray`].
75    ///
76    /// This mode will deduplicate all overlapping list views, such that the [`ListViewArray`] looks
77    /// like a [`ListArray`] but with an additional `sizes` array.
78    ///
79    /// [`ListArray`]: crate::arrays::ListArray
80    MakeZeroCopyToList,
81
82    /// Removes any leading or trailing elements that are unused / not referenced by any views in
83    /// the [`ListViewArray`].
84    ///
85    /// If the referenced `[start, end)` bounds are already known, prefer calling
86    /// [`trim_elements`](ListViewArray::trim_elements) directly to avoid recomputing them.
87    TrimElements,
88
89    /// Equivalent to `MakeZeroCopyToList` plus `TrimElements`.
90    ///
91    /// An array that is not yet zero-copy to a [`ListArray`] is copied with only its valid lists'
92    /// elements, and its null lists come out empty. One that already is zero-copy only loses the
93    /// elements before its first list and after its last, so its null lists keep theirs; use
94    /// [`MakeExactWithEmptyNulls`](Self::MakeExactWithEmptyNulls) to drop those too.
95    ///
96    /// This is useful when concatenating multiple [`ListViewArray`]s together to create a new
97    /// [`ListViewArray`] that is also zero-copy to a [`ListArray`].
98    ///
99    /// [`ListArray`]: crate::arrays::ListArray
100    MakeExact,
101
102    /// Equivalent to `MakeExact`, but the null lists of an array that is already zero-copy to a
103    /// [`ListArray`] come out empty as well, so only the valid lists' elements are left.
104    ///
105    /// This is useful for a function that must not see elements no valid list shows, such as one
106    /// that can fail on a value. An array that is already zero-copy to a [`ListArray`] keeps its
107    /// offsets' and sizes' types, and is returned as it is when there is nothing to drop.
108    ///
109    /// [`ListArray`]: crate::arrays::ListArray
110    MakeExactWithEmptyNulls,
111
112    // TODO(connor)[ListView]: Implement some version of this.
113    /// Finds the shortest packing / overlapping of list elements.
114    ///
115    /// This problem is known to be NP-hard, so maybe when someone proves that P=NP we can implement
116    /// this algorithm (but in all seriousness there are many approximate algorithms that could
117    /// work well here).
118    OverlapCompression,
119}
120
121impl ListViewArray {
122    /// Rebuilds the [`ListViewArray`] according to the specified mode.
123    pub fn rebuild(
124        &self,
125        mode: ListViewRebuildMode,
126        ctx: &mut ExecutionCtx,
127    ) -> VortexResult<ListViewArray> {
128        if self.is_empty() {
129            // An empty array uses none of its elements, so every mode drops them.
130            return Ok(Canonical::empty(self.dtype()).into_listview());
131        }
132
133        match mode {
134            ListViewRebuildMode::MakeZeroCopyToList => self.rebuild_zero_copy_to_list(ctx),
135            ListViewRebuildMode::TrimElements => self.rebuild_trim_elements(ctx),
136            ListViewRebuildMode::MakeExact => self.rebuild_make_exact(ctx),
137            ListViewRebuildMode::MakeExactWithEmptyNulls => {
138                self.rebuild_make_exact_with_empty_nulls(ctx)
139            }
140            ListViewRebuildMode::OverlapCompression => {
141                vortex_bail!("ListViewRebuildMode::OverlapCompression is not implemented")
142            }
143        }
144    }
145
146    /// Rebuilds a non-empty [`ListViewArray`] over only the elements that valid lists reference:
147    /// nothing before the first list, after the last, between lists or under a null list.
148    fn rebuild_make_exact_with_empty_nulls(
149        &self,
150        ctx: &mut ExecutionCtx,
151    ) -> VortexResult<ListViewArray> {
152        if !self.is_zero_copy_to_list() {
153            return self.rebuild_make_exact(ctx);
154        }
155        let validity = self.validity()?;
156        // The lists are back to back, so the last one ends where the referenced elements do.
157        let last = self.len() - 1;
158        let end = self.offset_at(last, ctx) + self.size_at(last, ctx);
159        if validity.definitely_no_nulls()
160            && self.offset_at(0, ctx) == 0
161            && end == self.elements().len()
162        {
163            return Ok(self.clone());
164        }
165
166        let offsets = self.offsets().clone().execute::<PrimitiveArray>(ctx)?;
167        let offsets_ptype = offsets.ptype();
168        // Offsets are never negative, so they are rebuilt unsigned and reinterpreted back.
169        let offsets = offsets.reinterpret_cast(offsets_ptype.to_unsigned());
170        let valid = validity.execute_mask(self.len(), ctx)?;
171        match_each_unsigned_integer_ptype!(offsets.ptype(), |O| {
172            self.rebuild_back_to_back(offsets.as_slice::<O>(), offsets_ptype, end, &valid, ctx)
173        })
174    }
175
176    /// [`MakeExactWithEmptyNulls`](ListViewRebuildMode::MakeExactWithEmptyNulls) for an array that
177    /// is zero-copy to a list, whose lists start at `starts` and end at `end`.
178    fn rebuild_back_to_back<O: IntegerPType>(
179        &self,
180        starts: &[O],
181        offsets_ptype: PType,
182        end: usize,
183        valid: &Mask,
184        ctx: &mut ExecutionCtx,
185    ) -> VortexResult<ListViewArray> {
186        // A list holds elements if and only if the next one starts later.
187        let null_runs = null_runs_holding_elements(valid, |index| {
188            starts[index].as_() != starts.get(index + 1).map_or(end, |next| next.as_())
189        });
190        if null_runs.is_empty() && starts[0].as_() == 0 && end == self.elements().len() {
191            return Ok(self.clone());
192        }
193
194        let (elements, offsets) =
195            drop_unreferenced_elements(self.elements(), starts, end, &null_runs, ctx.allocator())?;
196        let elements = elements.optimize_ctx(ctx)?;
197        let offsets = PrimitiveArray::new(offsets.freeze(), Validity::NonNullable)
198            .reinterpret_cast(offsets_ptype)
199            .into_array();
200        let sizes = if null_runs.is_empty() {
201            self.sizes().clone()
202        } else {
203            let sizes = self.sizes().clone().execute::<PrimitiveArray>(ctx)?;
204            let sizes_ptype = sizes.ptype();
205            let sizes = sizes.reinterpret_cast(sizes_ptype.to_unsigned());
206            let sizes = match_each_unsigned_integer_ptype!(sizes.ptype(), |S| {
207                empty_runs(sizes.as_slice::<S>(), &null_runs, ctx.allocator())
208            });
209            sizes.reinterpret_cast(sizes_ptype).into_array()
210        };
211
212        // SAFETY: the lists stay back to back and in order over the elements kept: each valid list
213        // keeps its elements, and each null list that held elements is now empty.
214        Ok(unsafe {
215            ListViewArray::new_unchecked(elements, offsets, sizes, self.validity()?)
216                .with_zero_copy_to_list(true)
217        })
218    }
219
220    /// Rebuilds a [`ListViewArray`], removing all data overlaps and creating a flattened layout.
221    ///
222    /// This is useful when the `elements` child array of the [`ListViewArray`] might have
223    /// overlapping, duplicate, and garbage data, and we want to have fully sequential data like
224    /// a [`ListArray`].
225    ///
226    /// [`ListArray`]: crate::arrays::ListArray
227    fn rebuild_zero_copy_to_list(&self, ctx: &mut ExecutionCtx) -> VortexResult<ListViewArray> {
228        if self.is_zero_copy_to_list() {
229            // Note that since everything in `ListViewArray` is `Arc`ed, this is quite cheap.
230            return Ok(self.clone());
231        }
232
233        let offsets_ptype = self.offsets().dtype().as_ptype();
234        let sizes_ptype = self.sizes().dtype().as_ptype();
235
236        // One of the main purposes behind adding this "zero-copyable to `ListArray`" optimization
237        // is that we want to pass data to systems that expect Arrow data.
238        // The arrow specification only allows for `i32` and `i64` offset and sizes types, so in
239        // order to also make `ListView` zero-copyable to **Arrow**'s `ListArray` (not just Vortex's
240        // `ListArray`), we rebuild the offsets as 32-bit or 64-bit integer types.
241        // TODO(connor)[ListView]: This is true for `sizes` as well, we should do this conversion
242        // for sizes as well.
243        match_each_unsigned_integer_ptype!(sizes_ptype.to_unsigned(), |S| {
244            match offsets_ptype.to_unsigned() {
245                PType::U8 => self.naive_rebuild::<u8, u32, S>(ctx),
246                PType::U16 => self.naive_rebuild::<u16, u32, S>(ctx),
247                PType::U32 => self.naive_rebuild::<u32, u32, S>(ctx),
248                PType::U64 => self.naive_rebuild::<u64, u64, S>(ctx),
249                _ => unreachable!("invalid offsets PType"),
250            }
251        })
252    }
253
254    /// Picks between [`rebuild_with_take`](Self::rebuild_with_take) and
255    /// [`rebuild_with_piecewise`](Self::rebuild_with_piecewise) based on average list size.
256    fn naive_rebuild<O: IntegerPType, NewOffset: IntegerPType, S: IntegerPType>(
257        &self,
258        ctx: &mut ExecutionCtx,
259    ) -> VortexResult<ListViewArray> {
260        let sizes_canonical = self.sizes().clone().execute::<PrimitiveArray>(ctx)?;
261        let sizes_canonical =
262            sizes_canonical.reinterpret_cast(sizes_canonical.ptype().to_unsigned());
263        let total: u64 = sizes_canonical
264            .as_slice::<S>()
265            .iter()
266            .map(|s| (*s).as_() as u64)
267            .sum();
268        if Self::should_use_take(total, self.len()) {
269            self.rebuild_with_take::<O, NewOffset, S>(ctx)
270        } else {
271            self.rebuild_with_piecewise::<NewOffset, S>(ctx)
272        }
273    }
274
275    /// Returns `true` when we are confident that `rebuild_with_take` will
276    /// outperform `rebuild_with_piecewise`.
277    ///
278    /// Take is dramatically faster for small lists (often 10-100×) because it
279    /// avoids per-list builder overhead. LBL is the safer default for larger
280    /// lists since its sequential memcpy scales well. We only choose take when
281    /// the average list size is small enough that take clearly dominates.
282    fn should_use_take(total_output_elements: u64, num_lists: usize) -> bool {
283        if num_lists == 0 {
284            return true;
285        }
286        let avg = total_output_elements / num_lists as u64;
287        avg < 128
288    }
289
290    /// Rebuilds elements using a single bulk `take`: collect all element indices into a flat
291    /// `BufferMut<u64>`, perform a single `take`.
292    fn rebuild_with_take<O: IntegerPType, NewOffset: IntegerPType, S: IntegerPType>(
293        &self,
294        ctx: &mut ExecutionCtx,
295    ) -> VortexResult<ListViewArray> {
296        let new_offset_ptype = rebuilt_offset_ptype(self.offsets().dtype().as_ptype());
297        let size_ptype = self.sizes().dtype().as_ptype();
298
299        let offsets_canonical = self.offsets().clone().execute::<PrimitiveArray>(ctx)?;
300        let offsets_canonical =
301            offsets_canonical.reinterpret_cast(offsets_canonical.ptype().to_unsigned());
302        let offsets_slice = offsets_canonical.as_slice::<O>();
303        let sizes_canonical = self.sizes().clone().execute::<PrimitiveArray>(ctx)?;
304        let sizes_canonical =
305            sizes_canonical.reinterpret_cast(sizes_canonical.ptype().to_unsigned());
306        let sizes_slice = sizes_canonical.as_slice::<S>();
307
308        let len = offsets_slice.len();
309
310        let mut new_offsets = BufferMut::<NewOffset>::with_capacity(len);
311        let mut new_sizes = BufferMut::<S>::with_capacity(len);
312        let mut take_indices = BufferMut::<u64>::with_capacity(self.elements().len());
313
314        // Resolve validity to a mask once instead of probing it per row: `execute_is_valid`
315        // executes a scalar on every call for array-backed validity, which is O(len) work repeated
316        // `len` times.
317        let validity = self.validity()?.execute_mask(len, ctx)?;
318
319        let mut n_elements = NewOffset::zero();
320        for index in 0..len {
321            if !validity.value(index) {
322                new_offsets.push(n_elements);
323                new_sizes.push(S::zero());
324                continue;
325            }
326
327            let offset = offsets_slice[index];
328            let size = sizes_slice[index];
329            let start = offset.as_();
330            let stop = start + size.as_();
331
332            new_offsets.push(n_elements);
333            new_sizes.push(size);
334            take_indices.extend(start as u64..stop as u64);
335            n_elements += num_traits::cast(size).vortex_expect("Cast failed");
336        }
337
338        let elements = self.elements().take(take_indices.into_array())?;
339        // Built unsigned; reinterpret back to the signed-preserving result types.
340        let offsets = PrimitiveArray::new(new_offsets.freeze(), Validity::NonNullable)
341            .reinterpret_cast(new_offset_ptype)
342            .into_array();
343        let sizes = PrimitiveArray::new(new_sizes.freeze(), Validity::NonNullable)
344            .reinterpret_cast(size_ptype)
345            .into_array();
346
347        // SAFETY: offsets are sequential and non-overlapping, all (offset, size) pairs reference
348        // valid elements, and the validity array is preserved from the original.
349        Ok(unsafe {
350            ListViewArray::new_unchecked(elements, offsets, sizes, self.validity()?)
351                .with_zero_copy_to_list(true)
352        })
353    }
354
355    /// Rebuilds elements using one contiguous-run take over the element child.
356    fn rebuild_with_piecewise<NewOffset: IntegerPType, S: IntegerPType>(
357        &self,
358        ctx: &mut ExecutionCtx,
359    ) -> VortexResult<ListViewArray> {
360        let new_offset_ptype = rebuilt_offset_ptype(self.offsets().dtype().as_ptype());
361        let size_ptype = self.sizes().dtype().as_ptype();
362
363        let offsets_canonical = self.offsets().clone().execute::<PrimitiveArray>(ctx)?;
364        let offsets_canonical =
365            offsets_canonical.reinterpret_cast(offsets_canonical.ptype().to_unsigned());
366        let sizes_canonical = self.sizes().clone().execute::<PrimitiveArray>(ctx)?;
367        let sizes_canonical =
368            sizes_canonical.reinterpret_cast(sizes_canonical.ptype().to_unsigned());
369
370        let len = offsets_canonical.len();
371        let validity = self.validity()?;
372        let validity_mask = validity.execute_mask(len, ctx)?;
373
374        let ranges = match_each_unsigned_integer_ptype!(offsets_canonical.ptype(), |O| {
375            rebuild_ranges::<NewOffset, O, S>(
376                offsets_canonical.as_slice::<O>(),
377                sizes_canonical.as_slice::<S>(),
378                &validity_mask,
379            )
380        })?;
381
382        let RebuildRanges {
383            new_offsets,
384            new_sizes,
385            starts,
386            lengths,
387            elements_len,
388        } = ranges;
389        let constant_length = lengths
390            .first()
391            .copied()
392            .filter(|first| lengths.iter().all(|length| *length == *first));
393        let lengths = match constant_length {
394            Some(length) => ConstantArray::new(length, starts.len()).into_array(),
395            None => lengths.into_array(),
396        };
397
398        // SAFETY: range starts and lengths are derived from valid ListView metadata; elements_len
399        // is the sum of all generated range lengths. Multiplier 1 preserves contiguous ranges.
400        let multipliers = ConstantArray::new(1u64, starts.len()).into_array();
401        let element_indices = unsafe {
402            PiecewiseSequenceArray::new_unchecked(
403                starts.into_array(),
404                lengths,
405                multipliers,
406                elements_len,
407            )
408        };
409        let elements = self.elements().take(element_indices.into_array())?;
410
411        // Built unsigned; reinterpret back to the signed-preserving result types.
412        let offsets = PrimitiveArray::new(new_offsets.freeze(), Validity::NonNullable)
413            .reinterpret_cast(new_offset_ptype)
414            .into_array();
415        let sizes = PrimitiveArray::new(new_sizes.freeze(), Validity::NonNullable)
416            .reinterpret_cast(size_ptype)
417            .into_array();
418
419        // SAFETY: offsets are sequential and non-overlapping, all (offset, size) pairs reference
420        // valid elements, and validity is preserved from the original array.
421        Ok(unsafe {
422            ListViewArray::new_unchecked(elements, offsets, sizes, validity)
423                .with_zero_copy_to_list(true)
424        })
425    }
426
427    /// Rebuilds a [`ListViewArray`] by trimming any unused / unreferenced leading and trailing
428    /// elements, which is defined as a contiguous run of values in the `elements` array that are
429    /// not referenced by any views in the corresponding [`ListViewArray`].
430    fn rebuild_trim_elements(&self, ctx: &mut ExecutionCtx) -> VortexResult<ListViewArray> {
431        let (start, end) = self.referenced_element_bounds(ctx)?;
432
433        // SAFETY: we calculated valid start and end bounds
434        unsafe { self.trim_elements(start, end) }
435    }
436
437    /// Unsafely trims `elements` to the referenced half-open range `[start, end)`, adjusting every offset
438    /// down by `start`. The result preserves the original `is_zero_copy_to_list` flag.
439    ///
440    /// # SAFETY
441    ///
442    /// `start` must be the minimum value of `offsets`, and end should be the maximum value of `offsets[i] + size[i]`
443    /// over all indices `i` of offsets. Otherwise, `offsets` and `sizes` may hold references to elements that no longer exist
444    /// and the array will be corrupted.
445    pub unsafe fn trim_elements(&self, start: usize, end: usize) -> VortexResult<ListViewArray> {
446        let adjusted_offsets = match_each_integer_ptype!(self.offsets().dtype().as_ptype(), |O| {
447            let offset = <O as FromPrimitive>::from_usize(start)
448                .vortex_expect("unable to convert the min offset `start` into a `usize`");
449            let scalar = Scalar::primitive(offset, Nullability::NonNullable);
450
451            self.offsets()
452                .clone()
453                .numeric(
454                    ConstantArray::new(scalar, self.offsets().len()).into_array(),
455                    NumericOperator::Sub,
456                )
457                .vortex_expect("was somehow unable to adjust offsets down by their minimum")
458        });
459
460        let sliced_elements = self.elements().slice(start..end)?;
461
462        // SAFETY: The only thing we changed was the elements (which we verify through mins and
463        // maxes that all adjusted offsets + sizes are within the correct bounds), so the parameters
464        // are valid. And if the original array was zero-copyable to list, trimming elements doesn't
465        // change that property.
466        Ok(unsafe {
467            ListViewArray::new_unchecked(
468                sliced_elements,
469                adjusted_offsets,
470                self.sizes().clone(),
471                self.validity()?,
472            )
473            .with_zero_copy_to_list(self.is_zero_copy_to_list())
474        })
475    }
476
477    fn rebuild_make_exact(&self, ctx: &mut ExecutionCtx) -> VortexResult<ListViewArray> {
478        if self.is_zero_copy_to_list() {
479            self.rebuild_trim_elements(ctx)
480        } else {
481            // When we completely rebuild the `ListViewArray`, we get the benefit that we also trim
482            // any leading and trailing garbage data.
483            self.rebuild_zero_copy_to_list(ctx)
484        }
485    }
486}
487
488/// The sizes with the lists in `runs` emptied.
489fn empty_runs<S: IntegerPType>(
490    sizes: &[S],
491    runs: &[(usize, usize)],
492    allocator: &BufferAllocatorRef,
493) -> PrimitiveArray {
494    let mut emptied = BufferMut::with_capacity_in(sizes.len(), allocator.clone());
495    let mut from = 0;
496    for &(run_start, run_end) in runs {
497        emptied.extend_from_slice(&sizes[from..run_start]);
498        emptied.push_n(S::zero(), run_end - run_start);
499        from = run_end;
500    }
501    emptied.extend_from_slice(&sizes[from..]);
502    PrimitiveArray::new(emptied.freeze(), Validity::NonNullable)
503}
504
505struct RebuildRanges<NewOffset, S> {
506    new_offsets: BufferMut<NewOffset>,
507    new_sizes: BufferMut<S>,
508    starts: BufferMut<u64>,
509    lengths: BufferMut<u64>,
510    elements_len: usize,
511}
512
513fn rebuild_ranges<NewOffset, O, S>(
514    offsets: &[O],
515    sizes: &[S],
516    validity_mask: &Mask,
517) -> VortexResult<RebuildRanges<NewOffset, S>>
518where
519    NewOffset: IntegerPType,
520    O: IntegerPType,
521    S: IntegerPType,
522{
523    let len = offsets.len();
524    let mut new_offsets = BufferMut::<NewOffset>::with_capacity(len);
525    let mut new_sizes = BufferMut::<S>::with_capacity(len);
526    let mut starts = BufferMut::<u64>::with_capacity(len);
527    let mut lengths = BufferMut::<u64>::with_capacity(len);
528    let mut n_elements = NewOffset::zero();
529    let mut elements_len = 0usize;
530
531    for (index, is_valid) in validity_mask.iter().enumerate() {
532        if !is_valid {
533            new_offsets.push(n_elements);
534            new_sizes.push(S::zero());
535            starts.push(0);
536            lengths.push(0);
537            continue;
538        }
539
540        let size = sizes[index];
541        let start: usize = offsets[index].as_();
542        let length: usize = size.as_();
543        start.checked_add(length).ok_or_else(|| {
544            vortex_err!(
545                "ListView rebuild element range overflow for start {start} and length {length}"
546            )
547        })?;
548        elements_len = elements_len
549            .checked_add(length)
550            .ok_or_else(|| vortex_err!("ListView rebuild elements length overflow"))?;
551
552        new_offsets.push(n_elements);
553        new_sizes.push(size);
554        starts.push(start as u64);
555        lengths.push(length as u64);
556        n_elements += num_traits::cast(size).vortex_expect("Cast failed");
557    }
558
559    Ok(RebuildRanges {
560        new_offsets,
561        new_sizes,
562        starts,
563        lengths,
564        elements_len,
565    })
566}
567
568#[cfg(test)]
569mod tests {
570    use rand::RngExt;
571    use rand::SeedableRng;
572    use rand::rngs::StdRng;
573    use rstest::rstest;
574    use vortex_buffer::BitBuffer;
575    use vortex_error::VortexResult;
576
577    use super::super::tests::common::SESSION;
578    use super::ListViewRebuildMode;
579    use crate::ArrayRef;
580    use crate::ExecutionCtx;
581    use crate::IntoArray;
582    use crate::VortexSessionExecute;
583    use crate::arrays::BoolArray;
584    use crate::arrays::ListArray;
585    use crate::arrays::ListViewArray;
586    use crate::arrays::PrimitiveArray;
587    use crate::arrays::list::ListArraySlotsExt;
588    use crate::arrays::listview::ListViewArrayExt;
589    use crate::arrays::listview::ListViewArraySlotsExt;
590    use crate::assert_arrays_eq;
591    use crate::builtins::ArrayBuiltins;
592    use crate::dtype::DType;
593    use crate::dtype::Nullability;
594    use crate::dtype::PType;
595    use crate::validity::Validity;
596
597    #[rstest]
598    #[case::nothing_to_drop(&[1, 2], &[(0, 1), (1, 1)], &[true, true], true, &[1, 2], &[(0, 1), (1, 1)])]
599    #[case::leftovers_at_the_ends(
600        &[9, 1, 2, 9],
601        &[(1, 1), (2, 1)],
602        &[true, true],
603        true,
604        &[1, 2],
605        &[(0, 1), (1, 1)]
606    )]
607    #[case::null_list_holding_elements(
608        &[9, 1, 9, 2],
609        &[(1, 1), (2, 1), (3, 1)],
610        &[true, false, true],
611        true,
612        &[1, 2],
613        &[(0, 1), (1, 0), (1, 1)]
614    )]
615    #[case::gap_between_lists(&[1, 9, 2], &[(0, 1), (2, 1)], &[true, true], false, &[1, 2], &[(0, 1), (1, 1)])]
616    #[case::lists_out_of_order(
617        &[1, 2, 3, 9],
618        &[(2, 1), (0, 2)],
619        &[true, true],
620        false,
621        &[3, 1, 2],
622        &[(0, 1), (1, 2)]
623    )]
624    #[case::null_list_holding_elements_not_zero_copy(
625        &[9, 1, 9, 2],
626        &[(1, 1), (2, 1), (3, 1)],
627        &[true, false, true],
628        false,
629        &[1, 2],
630        &[(0, 1), (1, 0), (1, 1)]
631    )]
632    #[case::empty_null_list_with_leftovers_at_the_ends(
633        &[9, 1, 2, 9],
634        &[(1, 1), (2, 0), (2, 1)],
635        &[true, false, true],
636        true,
637        &[1, 2],
638        &[(0, 1), (1, 0), (1, 1)]
639    )]
640    #[case::every_list_null(
641        &[9, 9],
642        &[(0, 1), (1, 1)],
643        &[false, false],
644        true,
645        &[],
646        &[(0, 0), (0, 0)]
647    )]
648    #[case::empty_lists_with_leftovers(
649        &[9, 9],
650        &[(1, 0), (1, 0)],
651        &[true, true],
652        true,
653        &[],
654        &[(0, 0), (0, 0)]
655    )]
656    #[case::overlapping_lists(
657        &[1, 2, 3, 9],
658        &[(0, 3), (1, 2)],
659        &[true, true],
660        false,
661        &[1, 2, 3, 2, 3],
662        &[(0, 3), (3, 2)]
663    )]
664    fn test_rebuild_make_exact_with_empty_nulls(
665        #[case] elements: &[i32],
666        #[case] views: &[(u32, u32)],
667        #[case] validity: &[bool],
668        #[case] zero_copy_to_list: bool,
669        #[case] expected_elements: &[i32],
670        #[case] expected_views: &[(u32, u32)],
671    ) -> VortexResult<()> {
672        let mut ctx = SESSION.create_execution_ctx();
673        let view = ListViewArray::try_new(
674            PrimitiveArray::from_iter(elements.iter().copied()).into_array(),
675            PrimitiveArray::from_iter(views.iter().map(|(offset, _)| *offset)).into_array(),
676            PrimitiveArray::from_iter(views.iter().map(|(_, size)| *size)).into_array(),
677            Validity::from_iter(validity.iter().copied()),
678            &mut ctx,
679        )?;
680        // SAFETY: the cases marked zero-copy to a list have sorted lists with nothing between them.
681        let view = unsafe { view.with_zero_copy_to_list(zero_copy_to_list) };
682        let rebuilt = view.rebuild(ListViewRebuildMode::MakeExactWithEmptyNulls, &mut ctx)?;
683        assert!(rebuilt.is_zero_copy_to_list());
684        assert_arrays_eq!(
685            rebuilt.elements().clone(),
686            PrimitiveArray::from_iter(expected_elements.iter().copied()),
687            &mut ctx
688        );
689        assert_arrays_eq!(
690            rebuilt.offsets().clone(),
691            PrimitiveArray::from_iter(expected_views.iter().map(|(offset, _)| *offset)),
692            &mut ctx
693        );
694        assert_arrays_eq!(
695            rebuilt.sizes().clone(),
696            PrimitiveArray::from_iter(expected_views.iter().map(|(_, size)| *size)),
697            &mut ctx
698        );
699        assert_arrays_eq!(rebuilt, view, &mut ctx);
700        Ok(())
701    }
702
703    #[rstest]
704    #[case::non_nullable(Validity::NonNullable)]
705    #[case::empty_null_list(Validity::from_iter([true, false, true]))]
706    fn test_rebuild_make_exact_with_empty_nulls_returns_an_exact_list_view_as_is(
707        #[case] validity: Validity,
708    ) -> VortexResult<()> {
709        let mut ctx = SESSION.create_execution_ctx();
710        let view = ListViewArray::try_new(
711            PrimitiveArray::from_iter([1i32, 2, 3]).into_array(),
712            PrimitiveArray::from_iter([0u32, 1, 1]).into_array(),
713            PrimitiveArray::from_iter([1u32, 0, 2]).into_array(),
714            validity,
715            &mut ctx,
716        )?;
717        // SAFETY: the lists are sorted with nothing between them.
718        let view = unsafe { view.with_zero_copy_to_list(true) };
719        let rebuilt = view.rebuild(ListViewRebuildMode::MakeExactWithEmptyNulls, &mut ctx)?;
720        assert!(ArrayRef::ptr_eq(rebuilt.elements(), view.elements()));
721        assert!(ArrayRef::ptr_eq(rebuilt.offsets(), view.offsets()));
722        assert!(ArrayRef::ptr_eq(rebuilt.sizes(), view.sizes()));
723        Ok(())
724    }
725
726    /// `values` as a primitive array of `ptype`.
727    fn primitive_of(
728        values: impl IntoIterator<Item = u32>,
729        ptype: PType,
730        ctx: &mut ExecutionCtx,
731    ) -> VortexResult<ArrayRef> {
732        Ok(PrimitiveArray::from_iter(values)
733            .into_array()
734            .cast(DType::Primitive(ptype, Nullability::NonNullable))?
735            .execute::<PrimitiveArray>(ctx)?
736            .into_array())
737    }
738
739    /// Random lists with elements before, after and under null lists, rebuilt as a `ListArray`
740    /// and as list views with and without the zero-copy flag, against a reference that gathers
741    /// each valid list's elements back to back.
742    #[test]
743    fn test_compact_and_make_exact_with_empty_nulls_match_a_reference() -> VortexResult<()> {
744        const PTYPES: [PType; 5] = [PType::U8, PType::U16, PType::U64, PType::I32, PType::I64];
745        let u32_dtype = DType::Primitive(PType::U32, Nullability::NonNullable);
746        let mut ctx = SESSION.create_execution_ctx();
747        let mut rng = StdRng::seed_from_u64(0);
748        for _ in 0..500 {
749            let len = rng.random_range(0..10usize);
750            let mut offset = rng.random_range(0..3u32);
751            let mut offsets = vec![offset];
752            for _ in 0..len {
753                offset += rng.random_range(0..3u32);
754                offsets.push(offset);
755            }
756            let elements_len = offset + rng.random_range(0..3u32);
757            let valid: Vec<bool> = (0..len).map(|_| rng.random_bool(0.6)).collect();
758            let validity = match rng.random_range(0..3u8) {
759                0 if valid.iter().all(|valid| *valid) => Validity::NonNullable,
760                // Validity that starts mid-byte.
761                1 => Validity::Array(
762                    BoolArray::from_iter([false].into_iter().chain(valid.iter().copied()))
763                        .into_array()
764                        .slice(1..len + 1)?,
765                ),
766                _ => Validity::from_iter(valid.iter().copied()),
767            };
768            let ptype = PTYPES[rng.random_range(0..PTYPES.len())];
769
770            let mut expected_elements = Vec::new();
771            let mut expected_offsets = vec![0u32];
772            let mut kept = 0u32;
773            for (bounds, is_valid) in offsets.windows(2).zip(&valid) {
774                if *is_valid {
775                    expected_elements.extend(bounds[0]..bounds[1]);
776                    kept += bounds[1] - bounds[0];
777                }
778                expected_offsets.push(kept);
779            }
780            let expected_elements = PrimitiveArray::from_iter(expected_elements);
781            let expected_sizes =
782                PrimitiveArray::from_iter(expected_offsets.windows(2).map(|w| w[1] - w[0]));
783
784            let elements = PrimitiveArray::from_iter(0..elements_len).into_array();
785            let list = ListArray::try_new(
786                elements.clone(),
787                primitive_of(offsets.iter().copied(), ptype, &mut ctx)?,
788                validity.clone(),
789                &mut ctx,
790            )?;
791            let rebuilt = list.compact(&mut ctx)?;
792            assert_arrays_eq!(rebuilt.elements().clone(), expected_elements, &mut ctx);
793            assert_eq!(rebuilt.offsets().dtype(), list.offsets().dtype());
794            assert_arrays_eq!(
795                rebuilt.offsets().cast(u32_dtype.clone())?,
796                PrimitiveArray::from_iter(expected_offsets.iter().copied()),
797                &mut ctx
798            );
799            assert_arrays_eq!(rebuilt, list, &mut ctx);
800
801            for zero_copy_to_list in [true, false] {
802                let view = ListViewArray::try_new(
803                    elements.clone(),
804                    primitive_of(offsets[..len].iter().copied(), ptype, &mut ctx)?,
805                    primitive_of(offsets.windows(2).map(|w| w[1] - w[0]), ptype, &mut ctx)?,
806                    validity.clone(),
807                    &mut ctx,
808                )?;
809                // SAFETY: the views are a `ListArray`'s lists, sorted with nothing between them.
810                let view = unsafe { view.with_zero_copy_to_list(zero_copy_to_list) };
811                let rebuilt =
812                    view.rebuild(ListViewRebuildMode::MakeExactWithEmptyNulls, &mut ctx)?;
813                assert!(rebuilt.is_zero_copy_to_list());
814                assert_arrays_eq!(
815                    rebuilt.elements().clone(),
816                    expected_elements.clone(),
817                    &mut ctx
818                );
819                // The copy widens the offsets, so compare their values.
820                assert_arrays_eq!(
821                    rebuilt.offsets().cast(u32_dtype.clone())?,
822                    PrimitiveArray::from_iter(expected_offsets[..len].iter().copied()),
823                    &mut ctx
824                );
825                assert_arrays_eq!(
826                    rebuilt.sizes().cast(u32_dtype.clone())?,
827                    expected_sizes.clone(),
828                    &mut ctx
829                );
830                assert_arrays_eq!(rebuilt, view, &mut ctx);
831            }
832        }
833        Ok(())
834    }
835
836    #[test]
837    fn test_rebuild_flatten_removes_overlaps() -> VortexResult<()> {
838        let mut ctx = SESSION.create_execution_ctx();
839        // Create a list view with overlapping lists: [A, B, C]
840        // List 0: offset=0, size=3 -> [A, B, C]
841        // List 1: offset=1, size=2 -> [B, C] (overlaps with List 0)
842        let elements = PrimitiveArray::from_iter(vec![1i32, 2, 3]).into_array();
843        let offsets = PrimitiveArray::from_iter(vec![0u32, 1]).into_array();
844        let sizes = PrimitiveArray::from_iter(vec![3u32, 2]).into_array();
845
846        let listview =
847            ListViewArray::new(elements, offsets, sizes, Validity::NonNullable, &mut ctx);
848
849        let mut ctx = SESSION.create_execution_ctx();
850        let flattened = listview.rebuild(ListViewRebuildMode::MakeZeroCopyToList, &mut ctx)?;
851
852        // After flatten: elements should be [A, B, C, B, C] = [1, 2, 3, 2, 3]
853        // Lists should be sequential with no overlaps
854        assert_eq!(flattened.elements().len(), 5);
855
856        // Offsets should be sequential
857        assert_eq!(flattened.offset_at(0, &mut ctx), 0);
858        assert_eq!(flattened.size_at(0, &mut ctx), 3);
859        assert_eq!(flattened.offset_at(1, &mut ctx), 3);
860        assert_eq!(flattened.size_at(1, &mut ctx), 2);
861
862        // Verify the data is correct
863        assert_arrays_eq!(
864            flattened.list_elements_at(0, &mut ctx)?,
865            PrimitiveArray::from_iter([1i32, 2, 3]),
866            &mut ctx
867        );
868
869        assert_arrays_eq!(
870            flattened.list_elements_at(1, &mut ctx)?,
871            PrimitiveArray::from_iter([2i32, 3]),
872            &mut ctx
873        );
874        Ok(())
875    }
876
877    #[test]
878    fn test_rebuild_flatten_with_nullable() -> VortexResult<()> {
879        let mut ctx = SESSION.create_execution_ctx();
880        use crate::arrays::BoolArray;
881
882        // Create a nullable list view with a null list
883        let elements = PrimitiveArray::from_iter(vec![1i32, 2, 3]).into_array();
884        let offsets = PrimitiveArray::from_iter(vec![0u32, 1, 2]).into_array();
885        let sizes = PrimitiveArray::from_iter(vec![2u32, 1, 1]).into_array();
886        let validity = Validity::Array(
887            BoolArray::new(
888                BitBuffer::from(vec![true, false, true]),
889                Validity::NonNullable,
890            )
891            .into_array(),
892        );
893
894        let listview = ListViewArray::new(elements, offsets, sizes, validity, &mut ctx);
895
896        let mut ctx = SESSION.create_execution_ctx();
897        let flattened = listview.rebuild(ListViewRebuildMode::MakeZeroCopyToList, &mut ctx)?;
898
899        // Verify nullability is preserved
900        assert_eq!(flattened.dtype().nullability(), Nullability::Nullable);
901        assert!(flattened.validity()?.execute_is_valid(0, &mut ctx)?);
902        assert!(!flattened.validity()?.execute_is_valid(1, &mut ctx)?);
903        assert!(flattened.validity()?.execute_is_valid(2, &mut ctx)?);
904
905        // Verify valid lists contain correct data
906        assert_arrays_eq!(
907            flattened.list_elements_at(0, &mut ctx)?,
908            PrimitiveArray::from_iter([1i32, 2]),
909            &mut ctx
910        );
911
912        assert_arrays_eq!(
913            flattened.list_elements_at(2, &mut ctx)?,
914            PrimitiveArray::from_iter([3i32]),
915            &mut ctx
916        );
917        Ok(())
918    }
919
920    #[test]
921    fn test_rebuild_flatten_null_row_uses_valid_empty_range() -> VortexResult<()> {
922        let elements = PrimitiveArray::from_iter(vec![1i32, 2, 3, 4]).into_array();
923        let offsets = PrimitiveArray::from_iter(vec![0u32, 1, 2]).into_array();
924        let sizes = PrimitiveArray::from_iter(vec![1u32, 2, 2]).into_array();
925        let validity = Validity::from_iter([true, false, true]);
926
927        // SAFETY: all source ranges are valid, including the null row's non-empty range.
928        let listview = unsafe { ListViewArray::new_unchecked(elements, offsets, sizes, validity) };
929
930        let mut ctx = SESSION.create_execution_ctx();
931        let flattened = listview.rebuild(ListViewRebuildMode::MakeZeroCopyToList, &mut ctx)?;
932
933        assert_eq!(flattened.offset_at(0, &mut ctx), 0);
934        assert_eq!(flattened.size_at(0, &mut ctx), 1);
935        assert_eq!(flattened.offset_at(1, &mut ctx), 1);
936        assert_eq!(flattened.size_at(1, &mut ctx), 0);
937        assert_eq!(flattened.offset_at(2, &mut ctx), 1);
938        assert_eq!(flattened.size_at(2, &mut ctx), 2);
939        assert!(flattened.validity()?.execute_is_valid(0, &mut ctx)?);
940        assert!(!flattened.validity()?.execute_is_valid(1, &mut ctx)?);
941        assert!(flattened.validity()?.execute_is_valid(2, &mut ctx)?);
942
943        assert_arrays_eq!(
944            flattened.list_elements_at(0, &mut ctx)?,
945            PrimitiveArray::from_iter([1i32]),
946            &mut ctx
947        );
948        assert_arrays_eq!(
949            flattened.list_elements_at(2, &mut ctx)?,
950            PrimitiveArray::from_iter([3i32, 4]),
951            &mut ctx
952        );
953        Ok(())
954    }
955
956    #[rstest]
957    #[case::zero_copy_to_list(ListViewRebuildMode::MakeZeroCopyToList)]
958    #[case::trim_elements(ListViewRebuildMode::TrimElements)]
959    #[case::make_exact(ListViewRebuildMode::MakeExact)]
960    #[case::make_exact_with_empty_nulls(ListViewRebuildMode::MakeExactWithEmptyNulls)]
961    fn test_rebuild_empty_drops_elements(#[case] mode: ListViewRebuildMode) -> VortexResult<()> {
962        let mut ctx = SESSION.create_execution_ctx();
963        // No lists, but three elements left in the buffer.
964        let listview = ListViewArray::new(
965            PrimitiveArray::from_iter([1i32, 2, 3]).into_array(),
966            PrimitiveArray::from_iter::<[u32; 0]>([]).into_array(),
967            PrimitiveArray::from_iter::<[u32; 0]>([]).into_array(),
968            Validity::NonNullable,
969            &mut ctx,
970        );
971
972        let rebuilt = listview.rebuild(mode, &mut ctx)?;
973        assert!(rebuilt.is_empty());
974        assert_eq!(rebuilt.elements().len(), 0);
975        assert!(rebuilt.is_zero_copy_to_list());
976        Ok(())
977    }
978
979    #[test]
980    fn test_rebuild_trim_elements_basic() -> VortexResult<()> {
981        let mut ctx = SESSION.create_execution_ctx();
982        // Test trimming both leading and trailing unused elements while preserving gaps in the
983        // middle.
984        // Elements: [_, _, A, B, _, C, D, _, _]
985        //            0  1  2  3  4  5  6  7  8
986        // List 0: offset=2, size=2 -> [A, B]
987        // List 1: offset=5, size=2 -> [C, D]
988        // Should trim to: [A, B, _, C, D] with adjusted offsets.
989        let elements =
990            PrimitiveArray::from_iter(vec![99i32, 98, 1, 2, 97, 3, 4, 96, 95]).into_array();
991        let offsets = PrimitiveArray::from_iter(vec![2u32, 5]).into_array();
992        let sizes = PrimitiveArray::from_iter(vec![2u32, 2]).into_array();
993
994        let listview =
995            ListViewArray::new(elements, offsets, sizes, Validity::NonNullable, &mut ctx);
996
997        let mut ctx = SESSION.create_execution_ctx();
998        let trimmed = listview.rebuild(ListViewRebuildMode::TrimElements, &mut ctx)?;
999
1000        // After trimming: elements should be [A, B, _, C, D] = [1, 2, 97, 3, 4].
1001        assert_eq!(trimmed.elements().len(), 5);
1002
1003        // Offsets should be adjusted: old offset 2 -> new offset 0, old offset 5 -> new offset 3.
1004        assert_eq!(trimmed.offset_at(0, &mut ctx), 0);
1005        assert_eq!(trimmed.size_at(0, &mut ctx), 2);
1006        assert_eq!(trimmed.offset_at(1, &mut ctx), 3);
1007        assert_eq!(trimmed.size_at(1, &mut ctx), 2);
1008
1009        // Verify the data is correct.
1010        assert_arrays_eq!(
1011            trimmed.list_elements_at(0, &mut ctx)?,
1012            PrimitiveArray::from_iter([1i32, 2]),
1013            &mut ctx
1014        );
1015
1016        assert_arrays_eq!(
1017            trimmed.list_elements_at(1, &mut ctx)?,
1018            PrimitiveArray::from_iter([3i32, 4]),
1019            &mut ctx
1020        );
1021
1022        // Note that element at index 2 (97) is preserved as a gap.
1023        let all_elements = trimmed
1024            .elements()
1025            .clone()
1026            .execute::<PrimitiveArray>(&mut ctx)?;
1027        assert_eq!(all_elements.execute_scalar(2, &mut ctx)?, 97i32.into());
1028        Ok(())
1029    }
1030
1031    #[test]
1032    fn test_rebuild_flatten_large_lists_with_piecewise_indices() -> VortexResult<()> {
1033        let mut ctx = SESSION.create_execution_ctx();
1034        let elements = PrimitiveArray::from_iter(0i32..300).into_array();
1035        let offsets = PrimitiveArray::from_iter(vec![10u32, 0]).into_array();
1036        let sizes = PrimitiveArray::from_iter(vec![150u32, 130]).into_array();
1037        let listview =
1038            ListViewArray::new(elements, offsets, sizes, Validity::NonNullable, &mut ctx);
1039
1040        let flattened = listview.rebuild(ListViewRebuildMode::MakeZeroCopyToList, &mut ctx)?;
1041
1042        assert_eq!(flattened.elements().len(), 280);
1043        assert_eq!(flattened.offset_at(0, &mut ctx), 0);
1044        assert_eq!(flattened.size_at(0, &mut ctx), 150);
1045        assert_eq!(flattened.offset_at(1, &mut ctx), 150);
1046        assert_eq!(flattened.size_at(1, &mut ctx), 130);
1047
1048        assert_arrays_eq!(
1049            flattened.list_elements_at(0, &mut ctx)?,
1050            PrimitiveArray::from_iter(10i32..160),
1051            &mut ctx
1052        );
1053        assert_arrays_eq!(
1054            flattened.list_elements_at(1, &mut ctx)?,
1055            PrimitiveArray::from_iter(0i32..130),
1056            &mut ctx
1057        );
1058        Ok(())
1059    }
1060
1061    #[test]
1062    fn test_rebuild_with_trailing_nulls_regression() -> VortexResult<()> {
1063        let mut ctx = SESSION.create_execution_ctx();
1064        // Regression test for issue #5412
1065        // Tests that zero-copy-to-list arrays with trailing NULLs correctly calculate
1066        // offsets for NULL items to maintain no-overlap invariant
1067
1068        // Create a ListViewArray with trailing NULLs
1069        let elements = PrimitiveArray::from_iter(vec![1i32, 2, 3, 4]).into_array();
1070        let offsets = PrimitiveArray::from_iter(vec![0u32, 2, 0, 0]).into_array();
1071        let sizes = PrimitiveArray::from_iter(vec![2u32, 2, 0, 0]).into_array();
1072        let validity = Validity::from_iter(vec![true, true, false, false]);
1073
1074        let listview = ListViewArray::new(elements, offsets, sizes, validity, &mut ctx);
1075
1076        // First rebuild to make it zero-copy-to-list
1077        let mut ctx = SESSION.create_execution_ctx();
1078        let rebuilt = listview.rebuild(ListViewRebuildMode::MakeZeroCopyToList, &mut ctx)?;
1079        assert!(rebuilt.is_zero_copy_to_list());
1080
1081        // Verify NULL items have correct offsets (should not reuse previous offsets)
1082        // After rebuild: offsets should be [0, 2, 4, 4] for zero-copy-to-list
1083        assert_eq!(rebuilt.offset_at(0, &mut ctx), 0);
1084        assert_eq!(rebuilt.offset_at(1, &mut ctx), 2);
1085        assert_eq!(rebuilt.offset_at(2, &mut ctx), 4); // NULL should be at position 4
1086        assert_eq!(rebuilt.offset_at(3, &mut ctx), 4); // Second NULL also at position 4
1087
1088        // All sizes should be correct
1089        assert_eq!(rebuilt.size_at(0, &mut ctx), 2);
1090        assert_eq!(rebuilt.size_at(1, &mut ctx), 2);
1091        assert_eq!(rebuilt.size_at(2, &mut ctx), 0); // NULL has size 0
1092        assert_eq!(rebuilt.size_at(3, &mut ctx), 0); // NULL has size 0
1093
1094        // Now rebuild with MakeExact (which calls naive_rebuild then trim_elements)
1095        // This should not panic (issue #5412)
1096        let exact = rebuilt.rebuild(ListViewRebuildMode::MakeExact, &mut ctx)?;
1097
1098        // Verify the result is still valid
1099        assert!(exact.is_valid(0, &mut ctx)?);
1100        assert!(exact.is_valid(1, &mut ctx)?);
1101        assert!(!exact.is_valid(2, &mut ctx)?);
1102        assert!(!exact.is_valid(3, &mut ctx)?);
1103
1104        // Verify data is preserved
1105        assert_arrays_eq!(
1106            exact.list_elements_at(0, &mut ctx)?,
1107            PrimitiveArray::from_iter([1i32, 2]),
1108            &mut ctx
1109        );
1110
1111        assert_arrays_eq!(
1112            exact.list_elements_at(1, &mut ctx)?,
1113            PrimitiveArray::from_iter([3i32, 4]),
1114            &mut ctx
1115        );
1116        Ok(())
1117    }
1118
1119    /// Regression test for <https://github.com/vortex-data/vortex/issues/6773>.
1120    /// u32 offsets exceed u16::MAX, so u16 sizes are widened to u32 for the add.
1121    #[test]
1122    fn test_rebuild_trim_elements_offsets_wider_than_sizes() -> VortexResult<()> {
1123        let mut ctx = SESSION.create_execution_ctx();
1124        let mut elems = vec![0i32; 70_005];
1125        elems[70_000] = 10;
1126        elems[70_001] = 20;
1127        elems[70_002] = 30;
1128        elems[70_003] = 40;
1129        let elements = PrimitiveArray::from_iter(elems).into_array();
1130        let offsets = PrimitiveArray::from_iter(vec![70_000u32, 70_002]).into_array();
1131        let sizes = PrimitiveArray::from_iter(vec![2u16, 2]).into_array();
1132
1133        let listview =
1134            ListViewArray::new(elements, offsets, sizes, Validity::NonNullable, &mut ctx);
1135        let mut ctx = SESSION.create_execution_ctx();
1136        let trimmed = listview.rebuild(ListViewRebuildMode::TrimElements, &mut ctx)?;
1137        assert_arrays_eq!(
1138            trimmed.list_elements_at(1, &mut ctx)?,
1139            PrimitiveArray::from_iter([30i32, 40]),
1140            &mut ctx
1141        );
1142        Ok(())
1143    }
1144
1145    /// Regression test for <https://github.com/vortex-data/vortex/issues/6773>.
1146    /// u32 sizes exceed u16::MAX, so u16 offsets are widened to u32 for the add.
1147    #[test]
1148    fn test_rebuild_trim_elements_sizes_wider_than_offsets() -> VortexResult<()> {
1149        let mut ctx = SESSION.create_execution_ctx();
1150        let mut elems = vec![0i32; 70_001];
1151        elems[3] = 30;
1152        elems[4] = 40;
1153        let elements = PrimitiveArray::from_iter(elems).into_array();
1154        let offsets = PrimitiveArray::from_iter(vec![1u16, 3]).into_array();
1155        let sizes = PrimitiveArray::from_iter(vec![70_000u32, 2]).into_array();
1156
1157        let listview =
1158            ListViewArray::new(elements, offsets, sizes, Validity::NonNullable, &mut ctx);
1159        let mut ctx = SESSION.create_execution_ctx();
1160        let trimmed = listview.rebuild(ListViewRebuildMode::TrimElements, &mut ctx)?;
1161        assert_arrays_eq!(
1162            trimmed.list_elements_at(1, &mut ctx)?,
1163            PrimitiveArray::from_iter([30i32, 40]),
1164            &mut ctx
1165        );
1166        Ok(())
1167    }
1168
1169    /// Rebuild with signed offsets/sizes: exercises the unsigned-reinterpret read path and asserts
1170    /// the result offset/size dtypes preserve signedness (widened to >=32-bit for offsets).
1171    #[test]
1172    fn test_rebuild_preserves_signed_offset_and_size_types() -> VortexResult<()> {
1173        let mut ctx = SESSION.create_execution_ctx();
1174        use crate::arrays::listview::ListViewArraySlotsExt;
1175        use crate::dtype::PType;
1176
1177        // Overlapping lists force an actual rebuild rather than the zero-copy fast path.
1178        let elements = PrimitiveArray::from_iter(vec![1i32, 2, 3]).into_array();
1179        let offsets = PrimitiveArray::from_iter(vec![0i32, 1]).into_array();
1180        let sizes = PrimitiveArray::from_iter(vec![3i16, 2]).into_array();
1181
1182        let listview =
1183            ListViewArray::new(elements, offsets, sizes, Validity::NonNullable, &mut ctx);
1184        let mut ctx = SESSION.create_execution_ctx();
1185        let rebuilt = listview.rebuild(ListViewRebuildMode::MakeZeroCopyToList, &mut ctx)?;
1186
1187        // Values: [1,2,3] and [2,3].
1188        assert_arrays_eq!(
1189            rebuilt.list_elements_at(0, &mut ctx)?,
1190            PrimitiveArray::from_iter([1i32, 2, 3]),
1191            &mut ctx
1192        );
1193        assert_arrays_eq!(
1194            rebuilt.list_elements_at(1, &mut ctx)?,
1195            PrimitiveArray::from_iter([2i32, 3]),
1196            &mut ctx
1197        );
1198
1199        // Signed input -> signed result (offsets widened to i32, sizes kept i16).
1200        assert_eq!(rebuilt.offsets().dtype().as_ptype(), PType::I32);
1201        assert_eq!(rebuilt.sizes().dtype().as_ptype(), PType::I16);
1202        Ok(())
1203    }
1204
1205    // ── should_use_take heuristic tests ────────────────────────────────────
1206
1207    #[test]
1208    fn heuristic_small_lists_use_take() {
1209        // avg = 127 → take
1210        assert!(ListViewArray::should_use_take(127_000, 1_000));
1211        // avg = 128 → LBL
1212        assert!(!ListViewArray::should_use_take(128_000, 1_000));
1213    }
1214
1215    /// Regression test for <https://github.com/vortex-data/vortex/issues/6973>.
1216    /// Both offsets and sizes are u8, and offset + size exceeds u8::MAX.
1217    #[test]
1218    fn test_rebuild_trim_elements_sum_overflows_type() -> VortexResult<()> {
1219        let mut ctx = SESSION.create_execution_ctx();
1220        let elements = PrimitiveArray::from_iter(vec![0i32; 261]).into_array();
1221        let offsets = PrimitiveArray::from_iter(vec![215u8, 0]).into_array();
1222        let sizes = PrimitiveArray::from_iter(vec![46u8, 10]).into_array();
1223
1224        let listview =
1225            ListViewArray::new(elements, offsets, sizes, Validity::NonNullable, &mut ctx);
1226        let mut ctx = SESSION.create_execution_ctx();
1227        let trimmed = listview.rebuild(ListViewRebuildMode::TrimElements, &mut ctx)?;
1228
1229        // min(offsets) = 0, so nothing to trim; output should equal input.
1230        assert_arrays_eq!(trimmed, listview, &mut ctx);
1231        Ok(())
1232    }
1233}