Skip to main content

vortex_array/
patches.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4use std::fmt::Debug;
5use std::hash::Hash;
6use std::ops::Range;
7
8use fearless_simd::Level;
9use fearless_simd::Simd;
10use fearless_simd::dispatch;
11use fearless_simd_macros::simd;
12use num_traits::NumCast;
13use vortex_buffer::BitBuffer;
14use vortex_buffer::BitBufferMut;
15use vortex_buffer::Buffer;
16use vortex_buffer::BufferAllocatorRef;
17use vortex_buffer::BufferMut;
18use vortex_error::VortexError;
19use vortex_error::VortexExpect as _;
20use vortex_error::VortexResult;
21use vortex_error::vortex_bail;
22use vortex_error::vortex_ensure;
23use vortex_error::vortex_ensure_eq;
24use vortex_error::vortex_err;
25use vortex_mask::AllOr;
26use vortex_mask::Mask;
27use vortex_mask::MaskValues;
28use vortex_utils::aliases::hash_map::HashMap;
29
30use crate::ArrayProbe;
31use crate::ArrayRef;
32use crate::ArraySlots;
33use crate::Columnar;
34use crate::EncodingProbeState;
35use crate::ExecutionCtx;
36use crate::IntoArray;
37use crate::ProbeState;
38use crate::arrays::PiecewiseSequence;
39use crate::arrays::Primitive;
40use crate::arrays::PrimitiveArray;
41use crate::arrays::piecewise_sequence::constant_unsigned_usize;
42use crate::arrays::piecewise_sequence::contiguous_runs;
43use crate::arrays::piecewise_sequence::maybe_contiguous_slices;
44use crate::arrays::primitive::PrimitiveArrayExt;
45use crate::builtins::ArrayBuiltins;
46use crate::dtype::DType;
47use crate::dtype::IntegerPType;
48use crate::dtype::NativePType;
49use crate::dtype::Nullability;
50use crate::dtype::Nullability::NonNullable;
51use crate::dtype::PType;
52use crate::dtype::UnsignedPType;
53use crate::match_each_unsigned_integer_ptype;
54use crate::optimizer::ArrayOptimizer;
55use crate::scalar::Scalar;
56use crate::search_sorted::SearchResult;
57use crate::search_sorted::SearchSorted;
58use crate::search_sorted::SearchSortedPrimitiveArray;
59use crate::search_sorted::SearchSortedSide;
60use crate::search_sorted::decode_sorted_positions;
61use crate::validity::Validity;
62use crate::vtable::VTable;
63
64/// One patch index offset is stored for each chunk.
65/// This allows for constant time patch index lookups.
66pub const PATCH_CHUNK_SIZE: usize = 1024;
67
68#[derive(Copy, Clone, prost::Message)]
69pub struct PatchesMetadata {
70    #[prost(uint64, tag = "1")]
71    len: u64,
72    #[prost(uint64, tag = "2")]
73    offset: u64,
74    #[prost(enumeration = "PType", tag = "3")]
75    indices_ptype: i32,
76    #[prost(uint64, optional, tag = "4")]
77    chunk_offsets_len: Option<u64>,
78    #[prost(enumeration = "PType", optional, tag = "5")]
79    chunk_offsets_ptype: Option<i32>,
80    #[prost(uint64, optional, tag = "6")]
81    offset_within_chunk: Option<u64>,
82}
83
84impl PatchesMetadata {
85    #[inline]
86    pub fn new(
87        len: usize,
88        offset: usize,
89        indices_ptype: PType,
90        chunk_offsets_len: Option<usize>,
91        chunk_offsets_ptype: Option<PType>,
92        offset_within_chunk: Option<usize>,
93    ) -> Self {
94        Self {
95            len: len as u64,
96            offset: offset as u64,
97            indices_ptype: indices_ptype as i32,
98            chunk_offsets_len: chunk_offsets_len.map(|len| len as u64),
99            chunk_offsets_ptype: chunk_offsets_ptype.map(|pt| pt as i32),
100            offset_within_chunk: offset_within_chunk.map(|len| len as u64),
101        }
102    }
103
104    #[inline]
105    pub fn len(&self) -> VortexResult<usize> {
106        usize::try_from(self.len).map_err(|_| vortex_err!("len does not fit in usize"))
107    }
108
109    #[inline]
110    pub fn is_empty(&self) -> bool {
111        self.len == 0
112    }
113
114    #[inline]
115    pub fn offset(&self) -> VortexResult<usize> {
116        usize::try_from(self.offset).map_err(|_| vortex_err!("offset does not fit in usize"))
117    }
118
119    #[inline]
120    pub fn chunk_offsets_dtype(&self) -> VortexResult<Option<DType>> {
121        self.chunk_offsets_ptype
122            .map(|t| {
123                PType::try_from(t)
124                    .map_err(|e| vortex_err!("invalid i32 value {t} for PType: {}", e))
125                    .map(|ptype| DType::Primitive(ptype, NonNullable))
126            })
127            .transpose()
128    }
129
130    #[inline]
131    pub fn indices_dtype(&self) -> VortexResult<DType> {
132        let ptype = PType::try_from(self.indices_ptype).map_err(|e| {
133            vortex_err!("invalid i32 value {} for PType: {}", self.indices_ptype, e)
134        })?;
135        vortex_ensure!(
136            ptype.is_unsigned_int(),
137            "Patch indices must be unsigned integers"
138        );
139        Ok(DType::Primitive(ptype, NonNullable))
140    }
141}
142
143/// Metadata stored in an array's data struct for reconstructing [`Patches`] from slots.
144///
145/// The actual patch arrays (indices, values, chunk_offsets) live in the array's
146/// slots. This struct stores only the scalar metadata needed to reassemble them.
147#[derive(Clone, Debug, Hash, PartialEq, Eq)]
148pub struct PatchesData {
149    offset: usize,
150    offset_within_chunk: Option<usize>,
151}
152
153/// What a repeated probe keeps for the patches of the array it reads: the patch indices,
154/// decoded on its first read so that later reads binary search a plain buffer.
155///
156/// Encodings with patches use it as, or inside, their
157/// [`OperationsVTable::ProbeState`](crate::vtable::OperationsVTable::ProbeState) and read
158/// through [`Patches::probe_patched`].
159#[derive(Debug, Default)]
160pub struct PatchesProbeState {
161    indices: Option<Buffer<u64>>,
162}
163
164impl PatchesProbeState {
165    /// The decoded patch indices, decoding `indices` on the first call.
166    fn indices(
167        &mut self,
168        indices: &ArrayRef,
169        ctx: &mut ExecutionCtx,
170    ) -> VortexResult<&Buffer<u64>> {
171        if self.indices.is_none() {
172            self.indices = Some(decode_sorted_positions(indices, ctx)?);
173        }
174        Ok(self.indices.as_ref().vortex_expect("decoded above"))
175    }
176}
177
178impl AsMut<PatchesProbeState> for PatchesProbeState {
179    fn as_mut(&mut self) -> &mut PatchesProbeState {
180        self
181    }
182}
183
184/// Slot indices for the three patch components within a slot array.
185#[derive(Copy, Clone, Debug)]
186pub struct PatchSlotIndices {
187    pub indices: usize,
188    pub values: usize,
189    pub chunk_offsets: usize,
190}
191
192impl PatchesData {
193    /// Extract patch metadata from an existing [`Patches`].
194    pub fn from_patches(patches: &Patches) -> Self {
195        Self {
196            offset: patches.offset(),
197            offset_within_chunk: patches.offset_within_chunk(),
198        }
199    }
200
201    /// Reconstruct patches from the given slot positions.
202    ///
203    /// Returns `None` if `patches_data` is `None`.
204    /// Panics if `patches_data` is `Some` but the indices or values slots are missing.
205    pub fn patches_from_slots(
206        patches_data: Option<&Self>,
207        len: usize,
208        slots: &[Option<ArrayRef>],
209        slot_idx: PatchSlotIndices,
210    ) -> Option<Patches> {
211        let data = patches_data?;
212        let indices = slots[slot_idx.indices]
213            .as_ref()
214            .vortex_expect("patches_data is set but patch_indices slot is missing");
215        let values = slots[slot_idx.values]
216            .as_ref()
217            .vortex_expect("patches_data is set but patch_values slot is missing");
218        Some(unsafe {
219            Patches::new_unchecked(
220                len,
221                data.offset,
222                indices.clone(),
223                values.clone(),
224                slots[slot_idx.chunk_offsets].clone(),
225                data.offset_within_chunk,
226            )
227        })
228    }
229
230    /// Push 3 patch slots (indices, values, chunk_offsets) onto a slot vector.
231    ///
232    /// If `patches` is `None`, pushes three `None` entries.
233    pub fn push_slots(slots: &mut ArraySlots, patches: Option<&Patches>) {
234        match patches {
235            Some(p) => {
236                slots.push(Some(p.indices().clone()));
237                slots.push(Some(p.values().clone()));
238                slots.push(p.chunk_offsets().clone());
239            }
240            None => {
241                slots.push(None);
242                slots.push(None);
243                slots.push(None);
244            }
245        }
246    }
247
248    /// Returns the patch offset.
249    #[inline]
250    pub fn offset(&self) -> usize {
251        self.offset
252    }
253
254    /// Returns the offset within the first chunk, if chunk offsets are present.
255    #[inline]
256    pub fn offset_within_chunk(&self) -> Option<usize> {
257        self.offset_within_chunk
258    }
259}
260
261/// The owned components of [`Patches`], as returned by [`Patches::into_parts`].
262pub struct PatchesParts {
263    pub array_len: usize,
264    pub offset: usize,
265    pub indices: ArrayRef,
266    pub values: ArrayRef,
267    pub chunk_offsets: Option<ArrayRef>,
268    pub offset_within_chunk: Option<usize>,
269}
270
271/// A helper for working with patched arrays.
272#[derive(Debug, Clone)]
273pub struct Patches {
274    array_len: usize,
275    offset: usize,
276    indices: ArrayRef,
277    values: ArrayRef,
278    /// Stores the patch index offset for each chunk.
279    ///
280    /// This allows us to lookup the patches for a given chunk in constant time via
281    /// `patch_indices[chunk_offsets[i]..chunk_offsets[i+1]]`.
282    ///
283    /// This is optional for compatibility reasons.
284    chunk_offsets: Option<ArrayRef>,
285    /// Chunk offsets are only sliced off in case the slice is fully
286    /// outside of the chunk range.
287    ///
288    /// Though the range for indices and values is sliced in terms of
289    /// individual elements, not chunks. To account for that we do a
290    /// saturating sub when adjusting the indices based on the chunk offset.
291    ///
292    /// `offset_within_chunk` is necessary in order to keep track of how many
293    /// elements were sliced off within the chunk.
294    offset_within_chunk: Option<usize>,
295}
296
297impl Patches {
298    pub fn new(
299        array_len: usize,
300        offset: usize,
301        indices: ArrayRef,
302        values: ArrayRef,
303        chunk_offsets: Option<ArrayRef>,
304        ctx: &mut ExecutionCtx,
305    ) -> VortexResult<Self> {
306        vortex_ensure_eq!(indices.len(), values.len());
307        vortex_ensure!(
308            indices.dtype().is_unsigned_int() && !indices.dtype().is_nullable(),
309            "Patch indices must be non-nullable unsigned integers, got {:?}",
310            indices.dtype()
311        );
312
313        vortex_ensure!(
314            indices.len() <= array_len,
315            "Patch indices must be shorter than the array length"
316        );
317        vortex_ensure!(!indices.is_empty(), "Patch indices must not be empty");
318
319        // Perform validation of components when they are host-resident.
320        // This is not possible to do eagerly when the data is on GPU memory.
321        if indices.is_host() && values.is_host() {
322            let max = usize::try_from(&indices.execute_scalar(indices.len() - 1, ctx)?)
323                .map_err(|_| vortex_err!("indices must be a number"))?;
324            vortex_ensure!(
325                max - offset < array_len,
326                "Patch indices {max:?}, offset {offset} are longer than the array length {array_len}"
327            );
328
329            #[cfg(debug_assertions)]
330            {
331                use crate::aggregate_fn::fns::is_sorted::is_strict_sorted;
332                assert!(
333                    is_strict_sorted(&indices, ctx).unwrap_or(false),
334                    "Patch indices must be strictly increasing"
335                );
336            }
337        }
338
339        Ok(Self {
340            array_len,
341            offset,
342            indices,
343            values,
344            chunk_offsets: chunk_offsets.clone(),
345            // Initialize with `Some(0)` only if `chunk_offsets` are set.
346            offset_within_chunk: chunk_offsets.map(|_| 0),
347        })
348    }
349
350    /// Reconstruct patches from serialized metadata and their child arrays.
351    ///
352    /// Preserves the number of patches sliced off within the first chunk. Metadata without this
353    /// field defaults to zero for compatibility with older arrays.
354    pub fn from_metadata(
355        array_len: usize,
356        metadata: &PatchesMetadata,
357        indices: ArrayRef,
358        values: ArrayRef,
359        chunk_offsets: Option<ArrayRef>,
360        ctx: &mut ExecutionCtx,
361    ) -> VortexResult<Self> {
362        let mut patches = Self::new(
363            array_len,
364            metadata.offset()?,
365            indices,
366            values,
367            chunk_offsets,
368            ctx,
369        )?;
370        if let Some(chunk_offsets) = &patches.chunk_offsets {
371            let offset_within_chunk = usize::try_from(metadata.offset_within_chunk())?;
372            let sliced_rows = patches.offset % PATCH_CHUNK_SIZE;
373            vortex_ensure!(
374                offset_within_chunk <= sliced_rows,
375                "Patch offset within chunk exceeds the sliced row count"
376            );
377
378            // A wrong offset can assign first-chunk patches to a later chunk during decoding.
379            // Check the boundary against the indices, not just the original chunk's patch count.
380            if chunk_offsets.len() > 1 && chunk_offsets.is_host() && patches.indices.is_host() {
381                let first_chunk_end = patches
382                    .offset
383                    .checked_add(PATCH_CHUNK_SIZE - sliced_rows)
384                    .ok_or_else(|| vortex_err!("Patch chunk boundary overflows usize"))?;
385                let [retained] =
386                    search_index_binary_search(&patches.indices, [first_chunk_end], ctx)?;
387                let retained = retained.to_index();
388                let expected_offset = patches
389                    .chunk_offset_at(1, ctx)?
390                    .checked_sub(patches.chunk_offset_at(0, ctx)?)
391                    .and_then(|count| count.checked_sub(retained))
392                    .ok_or_else(|| vortex_err!("Invalid patch chunk offsets"))?;
393                vortex_ensure_eq!(
394                    offset_within_chunk,
395                    expected_offset,
396                    "Patch offset within chunk disagrees with the patch indices"
397                );
398            }
399            patches.offset_within_chunk = Some(offset_within_chunk);
400        }
401        Ok(patches)
402    }
403
404    /// Construct new patches without validating any of the arguments
405    ///
406    /// # Safety
407    ///
408    /// Users have to assert that
409    /// * Indices and values have the same length
410    /// * Indices is an unsigned integer type
411    /// * Indices must be strictly increasing
412    /// * Last value in indices is smaller than array_len
413    pub unsafe fn new_unchecked(
414        array_len: usize,
415        offset: usize,
416        indices: ArrayRef,
417        values: ArrayRef,
418        chunk_offsets: Option<ArrayRef>,
419        offset_within_chunk: Option<usize>,
420    ) -> Self {
421        Self {
422            array_len,
423            offset,
424            indices,
425            values,
426            chunk_offsets,
427            offset_within_chunk,
428        }
429    }
430
431    #[inline]
432    pub fn array_len(&self) -> usize {
433        self.array_len
434    }
435
436    #[inline]
437    pub fn num_patches(&self) -> usize {
438        self.indices.len()
439    }
440
441    #[inline]
442    pub fn dtype(&self) -> &DType {
443        self.values.dtype()
444    }
445
446    #[inline]
447    pub fn indices(&self) -> &ArrayRef {
448        &self.indices
449    }
450
451    /// Consumes the patches and returns their components.
452    #[inline]
453    pub fn into_parts(self) -> PatchesParts {
454        PatchesParts {
455            array_len: self.array_len,
456            offset: self.offset,
457            indices: self.indices,
458            values: self.values,
459            chunk_offsets: self.chunk_offsets,
460            offset_within_chunk: self.offset_within_chunk,
461        }
462    }
463
464    #[inline]
465    pub fn into_indices(self) -> ArrayRef {
466        self.indices
467    }
468
469    #[inline]
470    pub fn indices_mut(&mut self) -> &mut ArrayRef {
471        &mut self.indices
472    }
473
474    #[inline]
475    pub fn values(&self) -> &ArrayRef {
476        &self.values
477    }
478
479    #[inline]
480    pub fn into_values(self) -> ArrayRef {
481        self.values
482    }
483
484    #[inline]
485    pub fn values_mut(&mut self) -> &mut ArrayRef {
486        &mut self.values
487    }
488
489    #[inline]
490    // Absolute offset: 0 if the array is unsliced.
491    pub fn offset(&self) -> usize {
492        self.offset
493    }
494
495    #[inline]
496    pub fn chunk_offsets(&self) -> &Option<ArrayRef> {
497        &self.chunk_offsets
498    }
499
500    #[inline]
501    pub fn chunk_offset_at(&self, idx: usize, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
502        let Some(chunk_offsets) = &self.chunk_offsets else {
503            vortex_bail!("chunk_offsets must be set to retrieve offset at index")
504        };
505
506        chunk_offsets
507            .execute_scalar(idx, ctx)?
508            .as_primitive()
509            .as_::<usize>()
510            .ok_or_else(|| vortex_err!("chunk offset does not fit in usize"))
511    }
512
513    /// Returns the number of patches sliced off from the current first chunk.
514    ///
515    /// When patches are sliced, the chunk offsets array is also sliced to only include
516    /// chunks that overlap with the slice range. However, the slice boundary may fall
517    /// in the middle of a chunk's patch range. This offset indicates how many patches
518    /// at the start of the first chunk should be skipped.
519    ///
520    /// Returns `None` if chunk offsets are not set.
521    #[inline]
522    pub fn offset_within_chunk(&self) -> Option<usize> {
523        self.offset_within_chunk
524    }
525
526    #[inline]
527    pub fn indices_ptype(&self) -> VortexResult<PType> {
528        PType::try_from(self.indices.dtype())
529            .map_err(|_| vortex_err!("indices dtype is not primitive"))
530    }
531
532    pub fn to_metadata(&self, len: usize, dtype: &DType) -> VortexResult<PatchesMetadata> {
533        if self.indices.len() > len {
534            vortex_bail!(
535                "Patch indices {} are longer than the array length {}",
536                self.indices.len(),
537                len
538            );
539        }
540        if self.values.dtype() != dtype {
541            vortex_bail!(
542                "Patch values dtype {} does not match array dtype {}",
543                self.values.dtype(),
544                dtype
545            );
546        }
547        let chunk_offsets_len = self.chunk_offsets.as_ref().map(|co| co.len());
548        let chunk_offsets_ptype = self.chunk_offsets.as_ref().map(|co| co.dtype().as_ptype());
549
550        Ok(PatchesMetadata::new(
551            self.indices.len(),
552            self.offset,
553            self.indices.dtype().as_ptype(),
554            chunk_offsets_len,
555            chunk_offsets_ptype,
556            self.offset_within_chunk,
557        ))
558    }
559
560    /// Get the patched value at a given index if it exists.
561    pub fn get_patched(
562        &self,
563        index: usize,
564        ctx: &mut ExecutionCtx,
565    ) -> VortexResult<Option<Scalar>> {
566        self.search_index(index, ctx)?
567            .to_found()
568            .map(|patch_idx| self.values().execute_scalar(patch_idx, ctx))
569            .transpose()
570    }
571
572    /// Searches for `index` in the indices array.
573    ///
574    /// Chooses between chunked search when [`Self::chunk_offsets`] is
575    /// available, and binary search otherwise. The `index` parameter is
576    /// adjusted by [`Self::offset`] for both.
577    ///
578    /// # Arguments
579    /// * `index` - The index to search for
580    ///
581    /// # Returns
582    /// * [`SearchResult::Found(patch_idx)`] - If a patch exists at this index, returns the
583    ///   position in the patches array
584    /// * [`SearchResult::NotFound(insertion_point)`] - If no patch exists, returns where
585    ///   a patch at this index would be inserted to maintain sorted order
586    ///
587    /// [`SearchResult::Found(patch_idx)`]: SearchResult::Found
588    /// [`SearchResult::NotFound(insertion_point)`]: SearchResult::NotFound
589    pub fn search_index(&self, index: usize, ctx: &mut ExecutionCtx) -> VortexResult<SearchResult> {
590        let [result] = self.search_indices([index], ctx)?;
591        Ok(result)
592    }
593
594    /// Searches for each of `indices`, as [`Self::search_index`] does for one.
595    ///
596    /// The searches share one probe of the chunk offsets, or one searcher over the patch indices,
597    /// rather than building one per search.
598    fn search_indices<const N: usize>(
599        &self,
600        indices: [usize; N],
601        ctx: &mut ExecutionCtx,
602    ) -> VortexResult<[SearchResult; N]> {
603        if self.chunk_offsets.is_some() {
604            return self.search_indices_chunked(indices, ctx);
605        }
606
607        search_index_binary_search(&self.indices, indices.map(|index| index + self.offset), ctx)
608    }
609
610    /// Constant time searches for each of `indices` in the indices array.
611    ///
612    /// First determines which chunk each target index falls into, then performs
613    /// a binary search within that chunk's range.
614    ///
615    /// Returns a [`SearchResult`] per index indicating either the exact patch index if found,
616    /// or the insertion point if not found.
617    ///
618    /// Returns an error if `chunk_offsets` or `offset_within_chunk` are not set.
619    fn search_indices_chunked<const N: usize>(
620        &self,
621        indices: [usize; N],
622        ctx: &mut ExecutionCtx,
623    ) -> VortexResult<[SearchResult; N]> {
624        let Some(chunk_offsets) = &self.chunk_offsets else {
625            vortex_bail!("chunk_offsets is required to be set")
626        };
627
628        // Every search reads the same chunk offsets, so they share one probe rather than
629        // building one per read as `Self::chunk_offset_at` does.
630        let mut probe = chunk_offsets.repeated_probe();
631        let mut chunk_offsets = ArrayProbe::Repeated(&mut probe);
632
633        let mut results = [SearchResult::NotFound(self.indices.len()); N];
634        for (result, index) in results.iter_mut().zip(indices) {
635            let Some(range) = self.chunk_patch_range(&mut chunk_offsets, index, ctx)? else {
636                continue;
637            };
638
639            let chunk_indices = self.indices.slice(range.clone())?.optimize_ctx(ctx)?;
640            let [found] = search_index_binary_search(&chunk_indices, [index + self.offset], ctx)?;
641
642            *result = match found {
643                SearchResult::Found(idx) => SearchResult::Found(range.start + idx),
644                SearchResult::NotFound(idx) => SearchResult::NotFound(range.start + idx),
645            };
646        }
647
648        Ok(results)
649    }
650
651    /// The range of positions in the indices array that holds the patches of `index`'s chunk,
652    /// read through `chunk_offsets`, or `None` if `index` is past the end of the array.
653    ///
654    /// Returns an error if `offset_within_chunk` is not set.
655    fn chunk_patch_range(
656        &self,
657        chunk_offsets: &mut ArrayProbe<'_>,
658        index: usize,
659        ctx: &mut ExecutionCtx,
660    ) -> VortexResult<Option<Range<usize>>> {
661        let Some(offset_within_chunk) = self.offset_within_chunk else {
662            vortex_bail!("offset_within_chunk is required to be set")
663        };
664
665        if index >= self.array_len() {
666            return Ok(None);
667        }
668
669        let chunk_idx = (index + self.offset % PATCH_CHUNK_SIZE) / PATCH_CHUNK_SIZE;
670        let num_chunks = chunk_offsets.array().len();
671        let mut chunk_offset_at = |idx: usize| -> VortexResult<usize> {
672            chunk_offsets
673                .execute_scalar(idx, ctx)?
674                .as_primitive()
675                .as_::<usize>()
676                .ok_or_else(|| vortex_err!("chunk offset does not fit in usize"))
677        };
678
679        // Patch index offsets are absolute and need to be offset by the first chunk of the current slice.
680        let base_offset = chunk_offset_at(0)?;
681
682        let patches_start_idx = relative_chunk_offset(chunk_offset_at(chunk_idx)?, base_offset)?
683            // Chunk offsets are only sliced off in case the slice is fully
684            // outside of the chunk range.
685            //
686            // Though the range for indices and values is sliced in terms of
687            // individual elements, not chunks. To account for that we do a
688            // saturating sub when adjusting the indices based on the chunk offset.
689            .saturating_sub(offset_within_chunk);
690
691        let patches_end_idx = if chunk_idx + 1 < num_chunks {
692            relative_chunk_offset(chunk_offset_at(chunk_idx + 1)?, base_offset)?
693                .saturating_sub(offset_within_chunk)
694                .min(self.indices.len())
695        } else {
696            self.indices.len()
697        };
698
699        Ok(Some(patches_start_idx..patches_end_idx))
700    }
701
702    /// Get the patched value at `index` of the array `state` reads, as [`Self::get_patched`]
703    /// does.
704    ///
705    /// `self` must be the patches held in the `slots` of that array. A repeated probe decodes the
706    /// patch indices into its [`PatchesProbeState`] on its first read, so every later read binary
707    /// searches a plain buffer and reads the value through the probe's values slot. A one-off
708    /// read takes the [`Self::get_patched`] path, which does not decode the whole index array.
709    pub fn probe_patched<V: VTable>(
710        &self,
711        state: &mut ProbeState<'_, V>,
712        slots: PatchSlotIndices,
713        index: usize,
714        ctx: &mut ExecutionCtx,
715    ) -> VortexResult<Option<Scalar>>
716    where
717        EncodingProbeState<V>: AsMut<PatchesProbeState>,
718    {
719        let (retained, mut children) = state.split();
720        let Some(retained) = retained else {
721            return self.get_patched(index, ctx);
722        };
723
724        let indices = retained.as_mut().indices(&self.indices, ctx)?;
725
726        // A needle past `u64` is past every patch index.
727        let Ok(needle) = u64::try_from(index + self.offset) else {
728            return Ok(None);
729        };
730        let Ok(position) = indices.binary_search(&needle) else {
731            return Ok(None);
732        };
733
734        children
735            .slot(slots.values)?
736            .ok_or_else(|| vortex_err!("patch values slot is missing"))?
737            .execute_scalar(position, ctx)
738            .map(Some)
739    }
740
741    /// Batch version of `search_index`.
742    ///
743    /// In contrast to `search_index`, this function requires `indices` as
744    /// well as `chunk_offsets` to be passed as slices. This is to avoid
745    /// redundant canonicalization and `scalar_at` lookups across calls.
746    fn search_index_chunked_batch<T, O>(
747        &self,
748        indices: &[T],
749        chunk_offsets: &[O],
750        index: T,
751    ) -> VortexResult<SearchResult>
752    where
753        T: UnsignedPType,
754        O: UnsignedPType,
755        usize: TryFrom<T>,
756        usize: TryFrom<O>,
757    {
758        let Some(offset_within_chunk) = self.offset_within_chunk else {
759            vortex_bail!("offset_within_chunk is required to be set")
760        };
761
762        let chunk_idx = {
763            let Ok(index) = usize::try_from(index) else {
764                // If the needle cannot be converted to usize, it's larger than all values in this array.
765                return Ok(SearchResult::NotFound(indices.len()));
766            };
767
768            if index >= self.array_len() {
769                return Ok(SearchResult::NotFound(self.indices().len()));
770            }
771
772            (index + self.offset % PATCH_CHUNK_SIZE) / PATCH_CHUNK_SIZE
773        };
774
775        let chunk_offset_at = |idx: usize| -> VortexResult<usize> {
776            let offset = *chunk_offsets
777                .get(idx)
778                .ok_or_else(|| vortex_err!("Patch chunk offsets have no entry for chunk {idx}"))?;
779            usize::try_from(offset)
780                .map_err(|_| vortex_err!("Patch chunk offset does not fit in usize"))
781        };
782
783        // Patch index offsets are absolute and need to be offset by the first chunk of the current slice.
784        let base_offset = chunk_offset_at(0)?;
785        let chunk_offset = relative_chunk_offset(chunk_offset_at(chunk_idx)?, base_offset)?;
786
787        let patches_start_idx = chunk_offset
788            // Chunk offsets are only sliced off in case the slice is fully
789            // outside of the chunk range.
790            //
791            // Though the range for indices and values is sliced in terms of
792            // individual elements, not chunks. To account for that we do a
793            // saturating sub when adjusting the indices based on the chunk offset.
794            .saturating_sub(offset_within_chunk);
795
796        let patches_end_idx = if chunk_idx + 1 < chunk_offsets.len() {
797            relative_chunk_offset(chunk_offset_at(chunk_idx + 1)?, base_offset)?
798                .saturating_sub(offset_within_chunk)
799                .min(indices.len())
800        } else {
801            self.indices.len()
802        };
803
804        let Some(offset) = T::from(self.offset) else {
805            // If the offset cannot be converted to T, it's larger than all values in this array.
806            return Ok(SearchResult::NotFound(indices.len()));
807        };
808
809        let chunk_indices = &indices[patches_start_idx..patches_end_idx];
810        let result = chunk_indices.search_sorted(&(index + offset), SearchSortedSide::Left)?;
811
812        Ok(match result {
813            SearchResult::Found(idx) => SearchResult::Found(patches_start_idx + idx),
814            SearchResult::NotFound(idx) => SearchResult::NotFound(patches_start_idx + idx),
815        })
816    }
817
818    /// Returns the minimum patch index
819    pub fn min_index(&self, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
820        let first = self
821            .indices
822            .execute_scalar(0, ctx)?
823            .as_primitive()
824            .as_::<usize>()
825            .ok_or_else(|| vortex_err!("index does not fit in usize"))?;
826        Ok(first - self.offset)
827    }
828
829    /// Returns the maximum patch index
830    pub fn max_index(&self, ctx: &mut ExecutionCtx) -> VortexResult<usize> {
831        let last = self
832            .indices
833            .execute_scalar(self.indices.len() - 1, ctx)?
834            .as_primitive()
835            .as_::<usize>()
836            .ok_or_else(|| vortex_err!("index does not fit in usize"))?;
837        Ok(last - self.offset)
838    }
839
840    /// Filter the patches by a mask, resulting in new patches for the filtered array.
841    pub fn filter(&self, mask: &Mask, ctx: &mut ExecutionCtx) -> VortexResult<Option<Self>> {
842        if mask.len() != self.array_len {
843            vortex_bail!(
844                "Filter mask length {} does not match array length {}",
845                mask.len(),
846                self.array_len
847            );
848        }
849
850        match mask {
851            Mask::AllTrue(_) => Ok(Some(self.clone())),
852            Mask::AllFalse(_) => Ok(None),
853            Mask::Values(mask_values) => {
854                let flat_indices = self.indices().clone().execute::<PrimitiveArray>(ctx)?;
855                match_each_unsigned_integer_ptype!(flat_indices.ptype(), |I| {
856                    filter_patches_with_mask(
857                        flat_indices.as_slice::<I>(),
858                        self.offset(),
859                        self.values(),
860                        mask_values,
861                        ctx.allocator(),
862                    )
863                })
864            }
865        }
866    }
867
868    /// Mask the patches, REMOVING the patches where the mask is true.
869    /// Unlike filter, this preserves the patch indices.
870    /// Unlike mask on a single array, this does not set masked values to null.
871    ///
872    /// Masking an array always yields a nullable result (see [`crate::scalar_fn::builtin::mask`]),
873    /// so the surviving patch values are widened to nullable to match the masked parent. Callers
874    /// therefore receive patches with the correct dtype and do not need to re-cast them.
875    // TODO(joe): make this lazy and remove the ctx.
876    pub fn mask(&self, mask: &Mask, ctx: &mut ExecutionCtx) -> VortexResult<Option<Self>> {
877        if mask.len() != self.array_len {
878            vortex_bail!(
879                "Filter mask length {} does not match array length {}",
880                mask.len(),
881                self.array_len
882            );
883        }
884
885        let filter_mask = match mask.bit_buffer() {
886            AllOr::All => return Ok(None),
887            AllOr::None => return self.clone().into_nullable_values().map(Some),
888            AllOr::Some(masked) => {
889                let patch_indices = self.indices().clone().execute::<PrimitiveArray>(ctx)?;
890                match_each_unsigned_integer_ptype!(patch_indices.ptype(), |P| {
891                    let patch_indices = patch_indices.as_slice::<P>();
892                    Mask::from_buffer(BitBuffer::collect_bool_in(
893                        patch_indices.len(),
894                        |i| {
895                            #[allow(clippy::cast_possible_truncation)]
896                            let idx = (patch_indices[i] as usize) - self.offset;
897                            !masked.value(idx)
898                        },
899                        ctx.allocator().clone(),
900                    ))
901                })
902            }
903        };
904
905        if filter_mask.all_false() {
906            return Ok(None);
907        }
908
909        // SAFETY: filtering indices/values with same mask maintains their 1:1 relationship
910        let filtered_indices = self.indices.filter(filter_mask.clone())?;
911        let filtered_values = self.values.filter(filter_mask)?;
912
913        Self {
914            array_len: self.array_len,
915            offset: self.offset,
916            indices: filtered_indices,
917            values: filtered_values,
918            // TODO(0ax1): Chunk offsets are invalid after a filter is applied.
919            chunk_offsets: None,
920            offset_within_chunk: self.offset_within_chunk,
921        }
922        .into_nullable_values()
923        .map(Some)
924    }
925
926    /// Widen the patch values to their nullable dtype, leaving indices and offsets untouched.
927    ///
928    /// The values stay logically unchanged (all currently-valid entries remain valid); only the
929    /// dtype's nullability flag is set. Used by [`Self::mask`], whose result must be nullable.
930    fn into_nullable_values(self) -> VortexResult<Self> {
931        if self.values.dtype().is_nullable() {
932            return Ok(self);
933        }
934        let nullable = self.values.dtype().as_nullable();
935        self.map_values(|values| values.cast(nullable))
936    }
937
938    /// Slice the patches by a range of the patched array.
939    pub fn slice(&self, range: Range<usize>, ctx: &mut ExecutionCtx) -> VortexResult<Option<Self>> {
940        let [slice_start, slice_end] = self.search_indices([range.start, range.end], ctx)?;
941        let slice_start_idx = slice_start.to_index();
942        let slice_end_idx = slice_end.to_index();
943
944        if slice_start_idx == slice_end_idx {
945            return Ok(None);
946        }
947
948        let values = self
949            .values()
950            .slice(slice_start_idx..slice_end_idx)?
951            .optimize_ctx(ctx)?;
952        let indices = self
953            .indices()
954            .slice(slice_start_idx..slice_end_idx)?
955            .optimize_ctx(ctx)?;
956
957        let new_chunk_offsets = self
958            .chunk_offsets
959            .as_ref()
960            .map(|chunk_offsets| -> VortexResult<ArrayRef> {
961                let chunk_relative_offset = self.offset % PATCH_CHUNK_SIZE;
962                let chunk_start_idx = (chunk_relative_offset + range.start) / PATCH_CHUNK_SIZE;
963                let chunk_end_idx = (chunk_relative_offset + range.end).div_ceil(PATCH_CHUNK_SIZE);
964                chunk_offsets
965                    .slice(chunk_start_idx..chunk_end_idx)?
966                    .optimize_ctx(ctx)
967            })
968            .transpose()?;
969
970        let offset_within_chunk = new_chunk_offsets
971            .as_ref()
972            .map(|new_chunk_offsets| -> VortexResult<usize> {
973                let new_chunk_base = new_chunk_offsets
974                    .execute_scalar(0, ctx)?
975                    .as_primitive()
976                    .as_::<usize>()
977                    .ok_or_else(|| vortex_err!("chunk offset does not fit in usize"))?;
978                let parent_chunk_base = self.chunk_offset_at(0, ctx)?;
979                let parent_within = self.offset_within_chunk.unwrap_or(0);
980                (parent_chunk_base + parent_within + slice_start_idx)
981                    .checked_sub(new_chunk_base)
982                    .ok_or_else(|| vortex_err!("Patch chunk offsets are not non-decreasing"))
983            })
984            .transpose()?;
985
986        Ok(Some(Self {
987            array_len: range.len(),
988            offset: range.start + self.offset(),
989            indices,
990            values,
991            chunk_offsets: new_chunk_offsets,
992            offset_within_chunk,
993        }))
994    }
995
996    // https://docs.google.com/spreadsheets/d/1D9vBZ1QJ6mwcIvV5wIL0hjGgVchcEnAyhvitqWu2ugU
997    const PREFER_MAP_WHEN_PATCHES_OVER_INDICES_LESS_THAN: f64 = 5.0;
998
999    fn is_map_faster_than_search(&self, take_indices: &PrimitiveArray) -> bool {
1000        (self.num_patches() as f64 / take_indices.len() as f64)
1001            < Self::PREFER_MAP_WHEN_PATCHES_OVER_INDICES_LESS_THAN
1002    }
1003
1004    /// Take the indices from the patches
1005    ///
1006    /// Any nulls in take_indices are added to the resulting patches.
1007    pub fn take_with_nulls(
1008        &self,
1009        take_indices: &ArrayRef,
1010        ctx: &mut ExecutionCtx,
1011    ) -> VortexResult<Option<Self>> {
1012        self.take_impl(take_indices, true, ctx)
1013    }
1014
1015    /// Take the indices from the patches.
1016    ///
1017    /// Any nulls in take_indices are ignored.
1018    pub fn take(
1019        &self,
1020        take_indices: &ArrayRef,
1021        ctx: &mut ExecutionCtx,
1022    ) -> VortexResult<Option<Self>> {
1023        self.take_impl(take_indices, false, ctx)
1024    }
1025
1026    fn take_impl(
1027        &self,
1028        take_indices: &ArrayRef,
1029        include_nulls: bool,
1030        ctx: &mut ExecutionCtx,
1031    ) -> VortexResult<Option<Self>> {
1032        if take_indices.is_empty() {
1033            return Ok(None);
1034        }
1035
1036        // Piecewise indices are non-nullable, so `include_nulls` makes no difference to them.
1037        if let Some(piecewise) = take_indices.as_opt::<PiecewiseSequence>()
1038            && let Some((starts, lengths)) = maybe_contiguous_slices(piecewise, ctx)?
1039            && let Some(runs) =
1040                SortedRuns::try_new(&starts, lengths, self.array_len, take_indices.len())
1041        {
1042            return self.take_sorted_runs(&starts, &runs, take_indices.len(), ctx);
1043        }
1044
1045        let take_indices = take_indices.clone().execute::<PrimitiveArray>(ctx)?;
1046        if self.is_map_faster_than_search(&take_indices) {
1047            self.take_map(take_indices, include_nulls, ctx)
1048        } else {
1049            self.take_search(take_indices, include_nulls, ctx)
1050        }
1051    }
1052
1053    /// Take ascending, non-overlapping runs of indices without expanding them.
1054    ///
1055    /// The runs and the sorted patch indices are merged by galloping along both, so the cost
1056    /// depends on the number of runs and patches rather than the number of indices.
1057    fn take_sorted_runs(
1058        &self,
1059        starts: &PrimitiveArray,
1060        runs: &SortedRuns,
1061        output_len: usize,
1062        ctx: &mut ExecutionCtx,
1063    ) -> VortexResult<Option<Self>> {
1064        let patch_indices = self.indices.clone().execute::<PrimitiveArray>(ctx)?;
1065        let mut new_indices = BufferMut::<u64>::with_capacity_in(
1066            self.num_patches().min(output_len),
1067            ctx.allocator().clone(),
1068        );
1069        let mut value_runs = ValueRuns::default();
1070        match_each_unsigned_integer_ptype!(patch_indices.ptype(), |P| {
1071            match_each_unsigned_integer_ptype!(starts.ptype(), |S| {
1072                merge_sorted_runs(
1073                    patch_indices.as_slice::<P>(),
1074                    self.offset,
1075                    starts.as_slice::<S>(),
1076                    runs,
1077                    &mut new_indices,
1078                    &mut value_runs,
1079                )
1080            })
1081        });
1082
1083        if new_indices.is_empty() {
1084            return Ok(None);
1085        }
1086        let values = value_runs.take_from(&self.values)?;
1087
1088        // SAFETY: there is one index and one value per matched patch. The indices are strictly
1089        // increasing non-nullable `u64` positions below `output_len`.
1090        Ok(Some(unsafe {
1091            Self::new_unchecked(output_len, 0, new_indices.into_array(), values, None, None)
1092        }))
1093    }
1094
1095    pub fn take_search(
1096        &self,
1097        take_indices: PrimitiveArray,
1098        include_nulls: bool,
1099        ctx: &mut ExecutionCtx,
1100    ) -> VortexResult<Option<Self>> {
1101        let take_indices_validity = take_indices.validity()?;
1102        // Take indices are non-negative; reinterpret to unsigned so the `TakeT` dimension
1103        // dispatches over 4 widths instead of 8.
1104        let take_indices_unsigned =
1105            take_indices.reinterpret_cast(take_indices.ptype().to_unsigned());
1106        let patch_indices = self.indices.clone().execute::<PrimitiveArray>(ctx)?;
1107        let chunk_offsets = self
1108            .chunk_offsets()
1109            .as_ref()
1110            .map(|co| co.clone().execute::<PrimitiveArray>(ctx))
1111            .transpose()?;
1112
1113        let take_validity = take_indices_validity.execute_mask(take_indices.len(), ctx)?;
1114        let (values_indices, new_indices) =
1115            match_each_unsigned_integer_ptype!(patch_indices.ptype(), |PatchT| {
1116                match_each_unsigned_integer_ptype!(take_indices_unsigned.ptype(), |TakeT| {
1117                    self.take_search_typed(
1118                        patch_indices.as_slice::<PatchT>(),
1119                        take_indices_unsigned.as_slice::<TakeT>(),
1120                        chunk_offsets.as_ref(),
1121                        take_validity,
1122                        include_nulls,
1123                        ctx.allocator(),
1124                    )
1125                })
1126            })?;
1127
1128        if new_indices.is_empty() {
1129            return Ok(None);
1130        }
1131
1132        let new_indices = new_indices.into_array();
1133        let new_array_len = take_indices.len();
1134        let values_validity = take_indices_validity.take(&new_indices)?;
1135
1136        Ok(Some(Self {
1137            array_len: new_array_len,
1138            offset: 0,
1139            indices: new_indices,
1140            values: self
1141                .values()
1142                .take(PrimitiveArray::new(values_indices, values_validity).into_array())?,
1143            chunk_offsets: None,
1144            offset_within_chunk: Some(0), // Reset when creating new Patches.
1145        }))
1146    }
1147
1148    fn take_search_typed<PatchT, TakeT>(
1149        &self,
1150        patch_indices: &[PatchT],
1151        take_indices: &[TakeT],
1152        chunk_offsets: Option<&PrimitiveArray>,
1153        take_validity: Mask,
1154        include_nulls: bool,
1155        allocator: &BufferAllocatorRef,
1156    ) -> VortexResult<(BufferMut<u64>, BufferMut<u64>)>
1157    where
1158        PatchT: UnsignedPType,
1159        TakeT: UnsignedPType,
1160        usize: TryFrom<PatchT>,
1161    {
1162        if let Some(chunk_offsets) = chunk_offsets {
1163            return match_each_unsigned_integer_ptype!(chunk_offsets.ptype(), |OffsetT| {
1164                self.take_search_chunked::<PatchT, TakeT, OffsetT>(
1165                    patch_indices,
1166                    take_indices,
1167                    chunk_offsets.as_slice::<OffsetT>(),
1168                    take_validity,
1169                    include_nulls,
1170                    allocator,
1171                )
1172            });
1173        }
1174
1175        take_indices_with_search_fn(
1176            patch_indices,
1177            take_indices,
1178            take_validity,
1179            include_nulls,
1180            allocator,
1181            |take_idx| {
1182                let Some(offset) = <PatchT as NumCast>::from(self.offset) else {
1183                    // An offset too large for `PatchT` exceeds every patch index.
1184                    return Ok(SearchResult::NotFound(patch_indices.len()));
1185                };
1186
1187                patch_indices.search_sorted(&(take_idx + offset), SearchSortedSide::Left)
1188            },
1189        )
1190    }
1191
1192    fn take_search_chunked<PatchT, TakeT, OffsetT>(
1193        &self,
1194        patch_indices: &[PatchT],
1195        take_indices: &[TakeT],
1196        chunk_offsets: &[OffsetT],
1197        take_validity: Mask,
1198        include_nulls: bool,
1199        allocator: &BufferAllocatorRef,
1200    ) -> VortexResult<(BufferMut<u64>, BufferMut<u64>)>
1201    where
1202        PatchT: UnsignedPType,
1203        TakeT: UnsignedPType,
1204        OffsetT: UnsignedPType,
1205        usize: TryFrom<PatchT> + TryFrom<OffsetT>,
1206    {
1207        take_indices_with_search_fn(
1208            patch_indices,
1209            take_indices,
1210            take_validity,
1211            include_nulls,
1212            allocator,
1213            |take_idx| self.search_index_chunked_batch(patch_indices, chunk_offsets, take_idx),
1214        )
1215    }
1216
1217    pub fn take_map(
1218        &self,
1219        take_indices: PrimitiveArray,
1220        include_nulls: bool,
1221        ctx: &mut ExecutionCtx,
1222    ) -> VortexResult<Option<Self>> {
1223        let indices = self.indices.clone().execute::<PrimitiveArray>(ctx)?;
1224        let new_length = take_indices.len();
1225        // Take indices are non-negative; reinterpret to unsigned (4 widths instead of 8).
1226        let take_indices_unsigned =
1227            take_indices.reinterpret_cast(take_indices.ptype().to_unsigned());
1228
1229        let min_index = self.min_index(ctx)?;
1230        let max_index = self.max_index(ctx)?;
1231
1232        let Some((new_sparse_indices, value_indices)) =
1233            match_each_unsigned_integer_ptype!(indices.ptype(), |Indices| {
1234                match_each_unsigned_integer_ptype!(take_indices_unsigned.ptype(), |TakeIndices| {
1235                    let take_validity = take_indices
1236                        .validity()?
1237                        .execute_mask(take_indices.len(), ctx)?;
1238                    let take_nullability = take_indices.validity()?.nullability();
1239                    let take_slice = take_indices_unsigned.as_slice::<TakeIndices>();
1240                    take_map::<_, TakeIndices>(
1241                        indices.as_slice::<Indices>(),
1242                        take_slice,
1243                        take_validity,
1244                        take_nullability,
1245                        self.offset(),
1246                        min_index,
1247                        max_index,
1248                        include_nulls,
1249                        ctx.allocator(),
1250                    )?
1251                })
1252            })
1253        else {
1254            return Ok(None);
1255        };
1256
1257        let taken_values = self.values().take(value_indices)?;
1258
1259        Ok(Some(Patches {
1260            array_len: new_length,
1261            offset: 0,
1262            indices: new_sparse_indices,
1263            values: taken_values,
1264            // TODO(0ax1): Chunk offsets are invalid after take is applied.
1265            chunk_offsets: None,
1266            offset_within_chunk: self.offset_within_chunk,
1267        }))
1268    }
1269
1270    pub fn map_values<F>(self, f: F) -> VortexResult<Self>
1271    where
1272        F: FnOnce(ArrayRef) -> VortexResult<ArrayRef>,
1273    {
1274        let values = f(self.values)?;
1275        if self.indices.len() != values.len() {
1276            vortex_bail!(
1277                "map_values must preserve length: expected {} received {}",
1278                self.indices.len(),
1279                values.len()
1280            )
1281        }
1282
1283        Ok(Self {
1284            array_len: self.array_len,
1285            offset: self.offset,
1286            indices: self.indices,
1287            values,
1288            chunk_offsets: self.chunk_offsets,
1289            offset_within_chunk: self.offset_within_chunk,
1290        })
1291    }
1292}
1293
1294/// Returns `chunk_offset` relative to `base_offset`, the first chunk's offset.
1295///
1296/// Offsets read from a file are untrusted, and a later chunk whose offset is below the first
1297/// would otherwise underflow.
1298fn relative_chunk_offset(chunk_offset: usize, base_offset: usize) -> VortexResult<usize> {
1299    chunk_offset
1300        .checked_sub(base_offset)
1301        .ok_or_else(|| vortex_err!("Patch chunk offsets are not non-decreasing"))
1302}
1303
1304/// Binary searches for each of `needles` in the indices array, sharing one searcher.
1305///
1306/// # Returns
1307/// Per needle, [`SearchResult::Found`] with the position if it exists, or
1308/// [`SearchResult::NotFound`] with the insertion point if not found.
1309fn search_index_binary_search<const N: usize>(
1310    indices: &ArrayRef,
1311    needles: [usize; N],
1312    ctx: &mut ExecutionCtx,
1313) -> VortexResult<[SearchResult; N]> {
1314    // A needle that does not fit the index type is a non-negative integer (a usize) larger than
1315    // all values in this array, so it is never found and sorts last.
1316    let mut results = [SearchResult::NotFound(indices.len()); N];
1317
1318    if let Some(primitive) = indices.as_opt::<Primitive>() {
1319        match_each_unsigned_integer_ptype!(primitive.ptype(), |T| {
1320            let values = primitive.as_slice::<T>();
1321            for (result, needle) in results.iter_mut().zip(needles) {
1322                if let Ok(needle) = T::try_from(needle) {
1323                    *result = values.search_sorted(&needle, SearchSortedSide::Left)?;
1324                }
1325            }
1326        });
1327        return Ok(results);
1328    }
1329
1330    match_each_unsigned_integer_ptype!(indices.dtype().as_ptype(), |T| {
1331        let searcher = SearchSortedPrimitiveArray::<T>::new(indices, ctx);
1332        for (result, needle) in results.iter_mut().zip(needles) {
1333            *result = searcher.search_sorted(&needle, SearchSortedSide::Left)?;
1334        }
1335    });
1336    Ok(results)
1337}
1338
1339#[expect(clippy::too_many_arguments)] // private function, can clean up one day
1340fn take_map<I: NativePType + Hash + Eq + TryFrom<usize>, T: NativePType>(
1341    indices: &[I],
1342    take_indices: &[T],
1343    take_validity: Mask,
1344    take_nullability: Nullability,
1345    indices_offset: usize,
1346    min_index: usize,
1347    max_index: usize,
1348    include_nulls: bool,
1349    allocator: &BufferAllocatorRef,
1350) -> VortexResult<Option<(ArrayRef, ArrayRef)>>
1351where
1352    usize: TryFrom<T>,
1353    VortexError: From<<I as TryFrom<usize>>::Error>,
1354{
1355    let offset_i = I::try_from(indices_offset)?;
1356
1357    let sparse_index_to_value_index: HashMap<I, usize> = indices
1358        .iter()
1359        .copied()
1360        .map(|idx| idx - offset_i)
1361        .enumerate()
1362        .map(|(value_index, sparse_index)| (sparse_index, value_index))
1363        .collect();
1364
1365    let mut new_sparse_indices =
1366        BufferMut::<u64>::with_capacity_in(take_indices.len(), allocator.clone());
1367    let mut value_indices =
1368        BufferMut::<u64>::with_capacity_in(take_indices.len(), allocator.clone());
1369
1370    for (idx_in_take, &take_idx) in take_indices.iter().enumerate() {
1371        let ti = usize::try_from(take_idx)
1372            .map_err(|_| vortex_err!("Failed to convert index to usize"))?;
1373
1374        // If we have to take nulls the take index doesn't matter, make it 0 for consistency
1375        let is_null = match take_validity.bit_buffer() {
1376            AllOr::All => false,
1377            AllOr::None => true,
1378            AllOr::Some(buf) => !buf.value(idx_in_take),
1379        };
1380        if is_null {
1381            if include_nulls {
1382                new_sparse_indices.push(idx_in_take as u64);
1383                value_indices.push(0);
1384            }
1385        } else if ti >= min_index && ti <= max_index {
1386            let ti_as_i = I::try_from(ti)
1387                .map_err(|_| vortex_err!("take index does not fit in index type"))?;
1388            if let Some(&value_index) = sparse_index_to_value_index.get(&ti_as_i) {
1389                new_sparse_indices.push(idx_in_take as u64);
1390                value_indices.push(value_index as u64);
1391            }
1392        }
1393    }
1394
1395    if new_sparse_indices.is_empty() {
1396        return Ok(None);
1397    }
1398
1399    let new_sparse_indices = new_sparse_indices.into_array();
1400    let values_validity =
1401        Validity::from_mask(take_validity, take_nullability).take(&new_sparse_indices)?;
1402    Ok(Some((
1403        new_sparse_indices,
1404        PrimitiveArray::new(value_indices, values_validity).into_array(),
1405    )))
1406}
1407
1408/// Filter patches with the provided mask (in flattened space).
1409///
1410/// The filter mask may contain indices that are non-patched. The return value of this function
1411/// is a new set of `Patches` with the indices relative to the provided `mask` rank, and the
1412/// patch values.
1413///
1414/// Choose between sparse searches and bitmap ranks without building the mask indices:
1415///
1416/// * Far more patches than selected rows: gallop through the patches.
1417/// * Very sparse patches or selections with cached mask indices: gallop the smaller side through
1418///   the larger.
1419/// * Otherwise: intersect the patches with the bitmap and rank only retained patches.
1420fn filter_patches_with_mask<T: IntegerPType>(
1421    patch_indices: &[T],
1422    offset: usize,
1423    patch_values: &ArrayRef,
1424    mask: &MaskValues,
1425    allocator: &BufferAllocatorRef,
1426) -> VortexResult<Option<Patches>> {
1427    let true_count = mask.true_count();
1428    let patch_count = patch_indices.len();
1429    let expected_matches = true_count.min(patch_count);
1430
1431    // The mask rank of each kept patch, and a bitmap over the original patches marking them.
1432    let mut new_patch_indices =
1433        BufferMut::<u64>::with_capacity_in(expected_matches, allocator.clone());
1434    let mut kept_patches = BitBufferMut::from_buffer(
1435        BufferMut::zeroed_in(patch_count.div_ceil(8), allocator.clone()),
1436        0,
1437        patch_count,
1438    );
1439
1440    // Gallop when patches far outnumber selected rows or when cached mask indices are very
1441    // sparse; otherwise intersect with the bitmap and rank only retained patches.
1442    if patch_count > true_count.saturating_mul(16) {
1443        gallop_patches_for_mask_indices(
1444            patch_indices,
1445            offset,
1446            mask,
1447            &mut new_patch_indices,
1448            &mut kept_patches,
1449        )?;
1450    } else if let Some(mask_indices) = mask.cached_indices()
1451        && expected_matches.saturating_mul(256) < mask.len()
1452    {
1453        if patch_count <= true_count {
1454            gallop_mask_indices_for_patches(
1455                patch_indices,
1456                offset,
1457                mask_indices,
1458                &mut new_patch_indices,
1459                &mut kept_patches,
1460            )?;
1461        } else {
1462            gallop_patches_for_mask_indices(
1463                patch_indices,
1464                offset,
1465                mask,
1466                &mut new_patch_indices,
1467                &mut kept_patches,
1468            )?;
1469        }
1470    } else {
1471        rank_patches_in_mask_bitmap(
1472            patch_indices,
1473            offset,
1474            mask.bit_buffer(),
1475            &mut new_patch_indices,
1476            &mut kept_patches,
1477        )?;
1478    }
1479
1480    let new_patch_values = match new_patch_indices.len() {
1481        0 => return Ok(None),
1482        kept if kept == patch_count => patch_values.clone(),
1483        _ => patch_values.filter(Mask::from_buffer(kept_patches.freeze()))?,
1484    };
1485    let new_patch_indices = new_patch_indices.into_array();
1486
1487    // SAFETY: there is one index and one value per kept patch. The indices are strictly
1488    // increasing non-nullable `u64` mask ranks below `true_count`.
1489    Ok(Some(unsafe {
1490        Patches::new_unchecked(
1491            true_count,
1492            0,
1493            new_patch_indices,
1494            new_patch_values,
1495            // TODO(0ax1): Chunk offsets are invalid after a filter is applied.
1496            None,
1497            None,
1498        )
1499    }))
1500}
1501
1502/// Returns the first position at or after `start` whose value is not less than `needle`.
1503///
1504/// The cost is logarithmic in the distance from `start` to the result.
1505fn gallop_lower_bound<T: Ord>(values: &[T], start: usize, needle: &T) -> usize {
1506    gallop_partition_point(values, start, |value| value < needle)
1507}
1508
1509/// Returns the first position at or after `start` for which `pred` is false, where `pred` is
1510/// true for a prefix of `values`.
1511///
1512/// The cost is logarithmic in the distance from `start` to the result.
1513#[inline]
1514fn gallop_partition_point<T>(
1515    values: &[T],
1516    start: usize,
1517    mut pred: impl FnMut(&T) -> bool,
1518) -> usize {
1519    let mut low = start;
1520    let mut high = start;
1521    let mut step = 1;
1522
1523    while high < values.len() && pred(&values[high]) {
1524        low = high + 1;
1525        high += step;
1526        step *= 2;
1527    }
1528
1529    let high = high.min(values.len());
1530    low + values[low..high].partition_point(pred)
1531}
1532
1533/// Finds the patch of each mask index, for masks that are sparser than the patches.
1534///
1535/// Mask indices after the last patch cannot match, so we skip them.
1536fn gallop_patches_for_mask_indices<T: IntegerPType>(
1537    patch_indices: &[T],
1538    offset: usize,
1539    mask: &MaskValues,
1540    new_patch_indices: &mut BufferMut<u64>,
1541    kept_patches: &mut BitBufferMut,
1542) -> VortexResult<()> {
1543    let Some(&last_patch_index) = patch_indices.last() else {
1544        return Ok(());
1545    };
1546    let last_mask_index = patch_index_to_usize(last_patch_index, offset)?;
1547
1548    let mut patch_position = 0;
1549    let mut mask_position = 0;
1550
1551    let mut visit = |mask_index: usize| {
1552        // At most the last patch index, so it fits in `T` and the search stays in bounds.
1553        let needle = <T as NumCast>::from(mask_index + offset)
1554            .vortex_expect("mask index is at most the last patch index");
1555
1556        patch_position = gallop_lower_bound(patch_indices, patch_position, &needle);
1557        if patch_indices[patch_position] == needle {
1558            new_patch_indices.push(mask_position as u64);
1559            kept_patches.set(patch_position);
1560            patch_position += 1;
1561        }
1562
1563        mask_position += 1;
1564    };
1565
1566    match mask.cached_indices() {
1567        Some(mask_indices) => {
1568            let end = mask_indices.partition_point(|&mask_index| mask_index <= last_mask_index);
1569            mask_indices[..end]
1570                .iter()
1571                .for_each(|&mask_index| visit(mask_index));
1572        }
1573        None => mask
1574            .bit_buffer()
1575            .slice(..=last_mask_index)
1576            .for_each_set_index(visit),
1577    }
1578
1579    Ok(())
1580}
1581
1582/// Finds the mask position of each patch, for patches that are not sparser than the mask.
1583fn gallop_mask_indices_for_patches<T: IntegerPType>(
1584    patch_indices: &[T],
1585    offset: usize,
1586    mask_indices: &[usize],
1587    new_patch_indices: &mut BufferMut<u64>,
1588    kept_patches: &mut BitBufferMut,
1589) -> VortexResult<()> {
1590    let mut mask_position = 0;
1591
1592    for (patch_position, patch_index) in patch_indices.iter().enumerate() {
1593        let index = patch_index_to_usize(*patch_index, offset)?;
1594
1595        mask_position = gallop_lower_bound(mask_indices, mask_position, &index);
1596        if mask_position == mask_indices.len() {
1597            break;
1598        }
1599
1600        if mask_indices[mask_position] == index {
1601            new_patch_indices.push(mask_position as u64);
1602            kept_patches.set(patch_position);
1603            mask_position += 1;
1604        }
1605    }
1606
1607    Ok(())
1608}
1609
1610/// Finds the mask position of each patch from the mask bitmap, without building the mask indices.
1611///
1612/// Each bitmap word is counted once. Rejected patches need no rank query; retained patches add
1613/// the population count of the bits preceding them in the current word.
1614fn rank_patches_in_mask_bitmap<T: IntegerPType>(
1615    patch_indices: &[T],
1616    offset: usize,
1617    mask: &BitBuffer,
1618    new_patch_indices: &mut BufferMut<u64>,
1619    kept_patches: &mut BitBufferMut,
1620) -> VortexResult<()> {
1621    // Compile scalar population counts with the CPU's features, including POPCNT on x86.
1622    dispatch!(Level::new(), simd => {
1623        rank_patches_in_mask_bitmap_simd(
1624            simd, patch_indices, offset, mask, new_patch_indices, kept_patches,
1625        )
1626    })
1627}
1628
1629#[simd]
1630fn rank_patches_in_mask_bitmap_simd<S: Simd, T: IntegerPType>(
1631    _: S,
1632    patch_indices: &[T],
1633    offset: usize,
1634    mask: &BitBuffer,
1635    new_patch_indices: &mut BufferMut<u64>,
1636    kept_patches: &mut BitBufferMut,
1637) -> VortexResult<()> {
1638    let chunks = mask.chunks();
1639    let mut words = chunks
1640        .iter()
1641        .chain(std::iter::once(chunks.remainder_bits()));
1642    let mut word = words.next().unwrap_or(0);
1643    let mut word_start = 0;
1644    let mut rank = 0;
1645
1646    for (patch_position, patch_index) in patch_indices.iter().enumerate() {
1647        let index = patch_index_to_usize(*patch_index, offset)?;
1648
1649        if mask.value(index) {
1650            while index - word_start >= 64 {
1651                rank += word.count_ones() as u64;
1652                word = words.next().vortex_expect("patch is within the mask");
1653                word_start += 64;
1654            }
1655            let preceding = word & ((1u64 << (index - word_start)) - 1);
1656            new_patch_indices.push(rank + preceding.count_ones() as u64);
1657            kept_patches.set(patch_position);
1658        }
1659    }
1660
1661    Ok(())
1662}
1663
1664#[inline]
1665fn patch_index_to_usize<T: IntegerPType>(patch_index: T, offset: usize) -> VortexResult<usize> {
1666    Ok(patch_index
1667        .to_usize()
1668        .ok_or_else(|| vortex_err!("patch index does not fit in usize"))?
1669        - offset)
1670}
1671
1672fn take_indices_with_search_fn<
1673    I: UnsignedPType,
1674    T: IntegerPType,
1675    F: Fn(I) -> VortexResult<SearchResult>,
1676>(
1677    indices: &[I],
1678    take_indices: &[T],
1679    take_validity: Mask,
1680    include_nulls: bool,
1681    allocator: &BufferAllocatorRef,
1682    search_fn: F,
1683) -> VortexResult<(BufferMut<u64>, BufferMut<u64>)> {
1684    let mut values_indices = BufferMut::with_capacity_in(take_indices.len(), allocator.clone());
1685    let mut new_indices = BufferMut::with_capacity_in(take_indices.len(), allocator.clone());
1686
1687    for (new_patch_idx, &take_idx) in take_indices.iter().enumerate() {
1688        if !take_validity.value(new_patch_idx) {
1689            if include_nulls {
1690                // For nulls, patch index doesn't matter - use 0 for consistency
1691                values_indices.push(0u64);
1692                new_indices.push(new_patch_idx as u64);
1693            }
1694            continue;
1695        } else {
1696            let search_result = match I::from(take_idx) {
1697                Some(idx) => search_fn(idx)?,
1698                None => SearchResult::NotFound(indices.len()),
1699            };
1700
1701            if let Some(patch_idx) = search_result.to_found() {
1702                values_indices.push(patch_idx as u64);
1703                new_indices.push(new_patch_idx as u64);
1704            }
1705        }
1706    }
1707
1708    Ok((values_indices, new_indices))
1709}
1710
1711/// The lengths of take index runs that are ascending, non-overlapping, and in bounds.
1712enum SortedRuns {
1713    /// Every run has this length.
1714    Constant(usize),
1715    /// The output offset of each run, followed by the total length.
1716    Offsets(Vec<usize>),
1717}
1718
1719impl SortedRuns {
1720    /// Returns `None` unless the runs are ascending, non-overlapping, and in bounds, and their
1721    /// lengths sum to `output_len`.
1722    fn try_new(
1723        starts: &PrimitiveArray,
1724        lengths: Columnar,
1725        array_len: usize,
1726        output_len: usize,
1727    ) -> Option<Self> {
1728        match lengths {
1729            Columnar::Constant(length) => {
1730                let length = constant_unsigned_usize(&length);
1731                let sorted = match_each_unsigned_integer_ptype!(starts.ptype(), |S| {
1732                    constant_runs_are_sorted(starts.as_slice::<S>(), length, array_len)
1733                });
1734                (sorted && starts.len().checked_mul(length) == Some(output_len))
1735                    .then_some(Self::Constant(length))
1736            }
1737            Columnar::Canonical(lengths) => {
1738                let lengths = lengths.into_primitive();
1739                let offsets = match_each_unsigned_integer_ptype!(starts.ptype(), |S| {
1740                    match_each_unsigned_integer_ptype!(lengths.ptype(), |L| {
1741                        sorted_run_offsets(
1742                            starts.as_slice::<S>(),
1743                            lengths.as_slice::<L>(),
1744                            array_len,
1745                        )
1746                    })
1747                })?;
1748                (offsets.last() == Some(&output_len)).then_some(Self::Offsets(offsets))
1749            }
1750        }
1751    }
1752
1753    #[inline]
1754    fn offset(&self, run: usize) -> usize {
1755        match self {
1756            Self::Constant(length) => run * length,
1757            Self::Offsets(offsets) => offsets[run],
1758        }
1759    }
1760
1761    #[inline]
1762    fn len(&self, run: usize) -> usize {
1763        match self {
1764            Self::Constant(length) => *length,
1765            Self::Offsets(offsets) => offsets[run + 1] - offsets[run],
1766        }
1767    }
1768}
1769
1770fn constant_runs_are_sorted<S: UnsignedPType>(
1771    starts: &[S],
1772    length: usize,
1773    array_len: usize,
1774) -> bool {
1775    let end = |start: &S| -> usize {
1776        let start: usize = start.as_();
1777        start.saturating_add(length)
1778    };
1779    starts.last().is_some_and(|last| end(last) <= array_len)
1780        && starts.windows(2).all(|w| end(&w[0]) <= w[1].as_())
1781}
1782
1783/// Returns the output offset of each run followed by the total length, or `None` unless the runs
1784/// are ascending, non-overlapping, and in bounds.
1785fn sorted_run_offsets<S: UnsignedPType, L: UnsignedPType>(
1786    starts: &[S],
1787    lengths: &[L],
1788    array_len: usize,
1789) -> Option<Vec<usize>> {
1790    let mut offsets = Vec::with_capacity(starts.len() + 1);
1791    let mut total = 0;
1792    let mut end = 0;
1793    for (&start, &length) in starts.iter().zip(lengths) {
1794        let (start, length): (usize, usize) = (start.as_(), length.as_());
1795        if start < end {
1796            return None;
1797        }
1798        end = start.checked_add(length).filter(|&end| end <= array_len)?;
1799        offsets.push(total);
1800        // Non-overlapping runs in bounds sum to at most `array_len`.
1801        total += length;
1802    }
1803    offsets.push(total);
1804    Some(offsets)
1805}
1806
1807/// Merges sorted take index runs with the sorted patch indices.
1808///
1809/// Gallops through the patches to the start of each run, and through the run starts to the next
1810/// patch, so runs and patches that do not meet are skipped in logarithmic time. Pushes the output
1811/// position of every matched patch to `new_indices` and its value position to `value_runs`.
1812fn merge_sorted_runs<P: UnsignedPType, S: UnsignedPType>(
1813    patch_indices: &[P],
1814    offset: usize,
1815    starts: &[S],
1816    runs: &SortedRuns,
1817    new_indices: &mut BufferMut<u64>,
1818    value_runs: &mut ValueRuns,
1819) {
1820    let mut patch = 0;
1821    let mut run = 0;
1822    while run < starts.len() {
1823        // Compare in the offset space of the stored patch indices.
1824        let start = starts[run].as_() + offset;
1825        patch = gallop_partition_point(patch_indices, patch, |p| p.as_() < start);
1826        let Some(next) = patch_indices.get(patch) else {
1827            break;
1828        };
1829
1830        let end = start + runs.len(run);
1831        let mut next = next.as_();
1832        if next < end {
1833            let matched = gallop_partition_point(patch_indices, patch + 1, |p| p.as_() < end);
1834            let output_offset = runs.offset(run);
1835            new_indices.extend(
1836                patch_indices[patch..matched]
1837                    .iter()
1838                    .map(|p| (p.as_() - start + output_offset) as u64),
1839            );
1840            value_runs.push(patch, matched - patch);
1841            patch = matched;
1842            let Some(after) = patch_indices.get(patch) else {
1843                break;
1844            };
1845            next = after.as_();
1846        }
1847
1848        // Move to the last run starting at or before the next patch, the only one that may
1849        // contain it.
1850        let following = gallop_partition_point(starts, run + 1, |s| s.as_() + offset <= next);
1851        run = (following - 1).max(run + 1);
1852    }
1853}
1854
1855/// Positions of the taken patch values, as contiguous runs.
1856#[derive(Default)]
1857struct ValueRuns {
1858    starts: Vec<u64>,
1859    lengths: Vec<u64>,
1860    len: usize,
1861}
1862
1863impl ValueRuns {
1864    /// Appends a run, extending the previous one when they meet.
1865    fn push(&mut self, start: usize, length: usize) {
1866        self.len += length;
1867        let (start, length) = (start as u64, length as u64);
1868        if let (Some(&last_start), Some(last_length)) =
1869            (self.starts.last(), self.lengths.last_mut())
1870            && last_start + *last_length == start
1871        {
1872            *last_length += length;
1873            return;
1874        }
1875        self.starts.push(start);
1876        self.lengths.push(length);
1877    }
1878
1879    /// Takes the runs from `values`, slicing when there is only one.
1880    fn take_from(self, values: &ArrayRef) -> VortexResult<ArrayRef> {
1881        if let [start] = self.starts.as_slice() {
1882            let start = usize::try_from(*start)?;
1883            return values.slice(start..start + self.len);
1884        }
1885        values.take(contiguous_runs(self.starts, self.lengths, self.len))
1886    }
1887}
1888
1889#[cfg(test)]
1890mod test {
1891    use std::ops::Range;
1892    use std::sync::LazyLock;
1893
1894    use rstest::rstest;
1895    use vortex_buffer::BitBuffer;
1896    use vortex_buffer::Buffer;
1897    use vortex_buffer::BufferMut;
1898    use vortex_buffer::buffer;
1899    use vortex_error::VortexExpect;
1900    use vortex_error::VortexResult;
1901    use vortex_mask::Mask;
1902    use vortex_session::VortexSession;
1903
1904    use crate::ArrayRef;
1905    use crate::IntoArray;
1906    use crate::VortexSessionExecute;
1907    use crate::arrays::ConstantArray;
1908    use crate::arrays::PiecewiseSequenceArray;
1909    use crate::assert_arrays_eq;
1910    use crate::dtype::PType;
1911    use crate::patches::Patches;
1912    use crate::patches::PatchesMetadata;
1913    use crate::patches::PrimitiveArray;
1914    use crate::search_sorted::SearchResult;
1915    use crate::validity::Validity;
1916
1917    static SESSION: LazyLock<VortexSession> = LazyLock::new(VortexSession::empty);
1918
1919    #[rstest]
1920    #[case::unchunked(false)]
1921    #[case::chunked(true)]
1922    fn test_from_metadata_without_offset_within_chunk(#[case] chunked: bool) -> VortexResult<()> {
1923        let mut ctx = SESSION.create_execution_ctx();
1924        let metadata = PatchesMetadata::new(
1925            3,
1926            0,
1927            PType::U32,
1928            chunked.then_some(3),
1929            chunked.then_some(PType::U32),
1930            None,
1931        );
1932        let patches = Patches::from_metadata(
1933            3072,
1934            &metadata,
1935            buffer![7u32, 1029, 2051].into_array(),
1936            buffer![11i32, 22, 33].into_array(),
1937            chunked.then(|| buffer![0u32, 1, 2].into_array()),
1938            &mut ctx,
1939        )?;
1940
1941        assert_eq!(patches.offset_within_chunk(), chunked.then_some(0));
1942        assert_eq!(
1943            patches.search_index(1029, &mut ctx)?,
1944            SearchResult::Found(1)
1945        );
1946        Ok(())
1947    }
1948
1949    #[rstest]
1950    fn test_from_metadata_rejects_inconsistent_chunk_offset(
1951        #[values(0, 2, 3, 501, usize::MAX)] offset_within_chunk: usize,
1952    ) {
1953        let mut ctx = SESSION.create_execution_ctx();
1954        // The original first chunk had patches at 100 and 500; slicing at 500 removed one.
1955        let metadata = PatchesMetadata::new(
1956            2,
1957            500,
1958            PType::U32,
1959            Some(2),
1960            Some(PType::U32),
1961            Some(offset_within_chunk),
1962        );
1963        let error = Patches::from_metadata(
1964            1000,
1965            &metadata,
1966            buffer![500u32, 1200].into_array(),
1967            buffer![11i32, 22].into_array(),
1968            Some(buffer![0u32, 2].into_array()),
1969            &mut ctx,
1970        )
1971        .expect_err("inconsistent patch offset must be rejected");
1972        assert!(error.to_string().contains("Patch offset within chunk"));
1973    }
1974
1975    #[rstest]
1976    #[case::single_chunk(900..901)]
1977    #[case::later_single_chunk(1500..1501)]
1978    #[case::multiple_chunks(900..2050)]
1979    fn test_from_metadata_short_slice(#[case] range: Range<usize>) -> VortexResult<()> {
1980        let mut ctx = SESSION.create_execution_ctx();
1981        let indices = PrimitiveArray::from_iter(0u32..3072).into_array();
1982        let patches = Patches::new(
1983            3072,
1984            0,
1985            indices.clone(),
1986            indices,
1987            Some(buffer![0u32, 1024, 2048].into_array()),
1988            &mut ctx,
1989        )?;
1990        let sliced = patches.slice(range, &mut ctx)?.expect("slice has patches");
1991        let metadata = sliced.to_metadata(sliced.array_len(), sliced.dtype())?;
1992        let read = Patches::from_metadata(
1993            sliced.array_len(),
1994            &metadata,
1995            sliced.indices().clone(),
1996            sliced.values().clone(),
1997            sliced.chunk_offsets().clone(),
1998            &mut ctx,
1999        )?;
2000
2001        assert_eq!(read.offset_within_chunk(), sliced.offset_within_chunk());
2002        assert_eq!(read.search_index(0, &mut ctx)?, SearchResult::Found(0));
2003        assert_arrays_eq!(read.values(), sliced.values(), &mut ctx);
2004        Ok(())
2005    }
2006
2007    #[cfg(debug_assertions)]
2008    #[test]
2009    #[should_panic(expected = "Patch indices must be strictly increasing")]
2010    fn test_new_rejects_repeated_indices() {
2011        let mut ctx = SESSION.create_execution_ctx();
2012        Patches::new(
2013            5,
2014            0,
2015            buffer![1u32, 1].into_array(),
2016            buffer![10i32, 20].into_array(),
2017            None,
2018            &mut ctx,
2019        )
2020        .unwrap();
2021    }
2022
2023    #[test]
2024    fn test_filter() {
2025        let mut ctx = SESSION.create_execution_ctx();
2026        let patches = Patches::new(
2027            100,
2028            0,
2029            buffer![10u32, 11, 20].into_array(),
2030            buffer![100, 110, 200].into_array(),
2031            None,
2032            &mut ctx,
2033        )
2034        .unwrap();
2035
2036        let filtered = patches
2037            .filter(&Mask::from_indices(100, vec![10, 20, 30]), &mut ctx)
2038            .unwrap()
2039            .unwrap();
2040
2041        assert_arrays_eq!(
2042            filtered.indices(),
2043            PrimitiveArray::from_iter([0u64, 1]),
2044            &mut ctx
2045        );
2046        assert_arrays_eq!(
2047            filtered.values(),
2048            PrimitiveArray::from_iter([100i32, 200]),
2049            &mut ctx
2050        );
2051    }
2052
2053    #[test]
2054    fn take_with_nulls() {
2055        let mut ctx = SESSION.create_execution_ctx();
2056        let patches = Patches::new(
2057            20,
2058            0,
2059            buffer![2u64, 9, 15].into_array(),
2060            PrimitiveArray::new(buffer![33_i32, 44, 55], Validity::AllValid).into_array(),
2061            None,
2062            &mut ctx,
2063        )
2064        .unwrap();
2065
2066        let taken = patches
2067            .take(
2068                &PrimitiveArray::new(buffer![9, 0], Validity::from_iter(vec![true, false]))
2069                    .into_array(),
2070                &mut ctx,
2071            )
2072            .unwrap()
2073            .unwrap();
2074        let values = taken.values();
2075        let primitive_indices = taken.indices();
2076        assert_eq!(taken.array_len(), 2);
2077        assert_arrays_eq!(
2078            values,
2079            PrimitiveArray::from_option_iter([Some(44i32)]),
2080            &mut ctx
2081        );
2082        assert_arrays_eq!(
2083            primitive_indices,
2084            PrimitiveArray::from_iter([0u64]),
2085            &mut ctx
2086        );
2087        assert_eq!(
2088            values
2089                .validity()
2090                .unwrap()
2091                .execute_mask(values.len(), &mut ctx)
2092                .unwrap(),
2093            Mask::from_iter(vec![true])
2094        );
2095    }
2096
2097    #[test]
2098    fn take_search_with_nulls_chunked() {
2099        let mut ctx = SESSION.create_execution_ctx();
2100        let patches = Patches::new(
2101            20,
2102            0,
2103            buffer![2u64, 9, 15].into_array(),
2104            buffer![33_i32, 44, 55].into_array(),
2105            Some(buffer![0u64].into_array()),
2106            &mut ctx,
2107        )
2108        .unwrap();
2109
2110        let taken = patches
2111            .take_search(
2112                PrimitiveArray::new(buffer![9, 0], Validity::from_iter([true, false])),
2113                true,
2114                &mut ctx,
2115            )
2116            .unwrap()
2117            .unwrap();
2118
2119        let values = taken.values();
2120        assert_eq!(taken.array_len(), 2);
2121        assert_arrays_eq!(
2122            values,
2123            PrimitiveArray::from_option_iter([Some(44i32), None]),
2124            &mut ctx
2125        );
2126        assert_arrays_eq!(
2127            taken.indices(),
2128            PrimitiveArray::from_iter([0u64, 1]),
2129            &mut ctx
2130        );
2131
2132        assert_eq!(
2133            values
2134                .validity()
2135                .unwrap()
2136                .execute_mask(values.len(), &mut ctx)
2137                .unwrap(),
2138            Mask::from_iter([true, false])
2139        );
2140    }
2141
2142    #[test]
2143    fn take_search_chunked_multiple_chunks() {
2144        let mut ctx = SESSION.create_execution_ctx();
2145        let patches = Patches::new(
2146            2048,
2147            0,
2148            buffer![100u64, 500, 1200, 1800].into_array(),
2149            buffer![10_i32, 20, 30, 40].into_array(),
2150            Some(buffer![0u64, 2].into_array()),
2151            &mut ctx,
2152        )
2153        .unwrap();
2154
2155        let taken = patches
2156            .take_search(
2157                PrimitiveArray::new(buffer![500, 1200, 999], Validity::AllValid),
2158                true,
2159                &mut ctx,
2160            )
2161            .unwrap()
2162            .unwrap();
2163
2164        assert_eq!(taken.array_len(), 3);
2165        assert_arrays_eq!(
2166            taken.values(),
2167            PrimitiveArray::from_option_iter([Some(20i32), Some(30)]),
2168            &mut ctx
2169        );
2170        assert_arrays_eq!(
2171            taken.indices(),
2172            PrimitiveArray::from_iter([0u64, 1]),
2173            &mut ctx
2174        );
2175    }
2176
2177    #[test]
2178    fn take_search_chunked_indices_with_no_patches() {
2179        let mut ctx = SESSION.create_execution_ctx();
2180        let patches = Patches::new(
2181            20,
2182            0,
2183            buffer![2u64, 9, 15].into_array(),
2184            buffer![33_i32, 44, 55].into_array(),
2185            Some(buffer![0u64].into_array()),
2186            &mut ctx,
2187        )
2188        .unwrap();
2189
2190        let taken = patches
2191            .take_search(
2192                PrimitiveArray::new(buffer![3, 4, 5], Validity::AllValid),
2193                true,
2194                &mut ctx,
2195            )
2196            .unwrap();
2197
2198        assert!(taken.is_none());
2199    }
2200
2201    #[test]
2202    fn take_search_chunked_interleaved() {
2203        let mut ctx = SESSION.create_execution_ctx();
2204        let patches = Patches::new(
2205            30,
2206            0,
2207            buffer![5u64, 10, 20, 25].into_array(),
2208            buffer![100_i32, 200, 300, 400].into_array(),
2209            Some(buffer![0u64].into_array()),
2210            &mut ctx,
2211        )
2212        .unwrap();
2213
2214        let taken = patches
2215            .take_search(
2216                PrimitiveArray::new(buffer![10, 15, 20, 99], Validity::AllValid),
2217                true,
2218                &mut ctx,
2219            )
2220            .unwrap()
2221            .unwrap();
2222
2223        assert_eq!(taken.array_len(), 4);
2224        assert_arrays_eq!(
2225            taken.values(),
2226            PrimitiveArray::from_option_iter([Some(200i32), Some(300)]),
2227            &mut ctx
2228        );
2229        assert_arrays_eq!(
2230            taken.indices(),
2231            PrimitiveArray::from_iter([0u64, 2]),
2232            &mut ctx
2233        );
2234    }
2235
2236    #[test]
2237    fn test_take_search_multiple_chunk_offsets() {
2238        let mut ctx = SESSION.create_execution_ctx();
2239        let patches = Patches::new(
2240            1500,
2241            0,
2242            BufferMut::from_iter(0..1500u64).into_array(),
2243            BufferMut::from_iter(0..1500i32).into_array(),
2244            Some(buffer![0u64, 1024u64].into_array()),
2245            &mut ctx,
2246        )
2247        .unwrap();
2248
2249        let taken = patches
2250            .take_search(
2251                PrimitiveArray::new(BufferMut::from_iter(0..1500u64), Validity::AllValid),
2252                false,
2253                &mut ctx,
2254            )
2255            .unwrap()
2256            .unwrap();
2257
2258        assert_eq!(taken.array_len(), 1500);
2259        assert_arrays_eq!(
2260            taken.indices(),
2261            PrimitiveArray::from_iter(0..1500u64),
2262            &mut ctx
2263        );
2264        assert_arrays_eq!(
2265            taken.values(),
2266            PrimitiveArray::from_option_iter((0..1500i32).map(Some)),
2267            &mut ctx
2268        );
2269    }
2270
2271    #[test]
2272    fn doubly_sliced() {
2273        let mut ctx = SESSION.create_execution_ctx();
2274        let values = buffer![15_u32, 135, 13531, 42].into_array();
2275        let indices = buffer![10_u64, 11, 50, 100].into_array();
2276
2277        let patches = Patches::new(101, 0, indices, values, None, &mut ctx).unwrap();
2278
2279        let sliced = patches.slice(15..100, &mut ctx).unwrap().unwrap();
2280        assert_eq!(sliced.array_len(), 100 - 15);
2281        assert_arrays_eq!(
2282            sliced.values(),
2283            PrimitiveArray::from_iter([13531u32]),
2284            &mut ctx
2285        );
2286
2287        assert_eq!(sliced.offset(), 15);
2288        assert_arrays_eq!(
2289            sliced.indices(),
2290            PrimitiveArray::from_iter([50u64]),
2291            &mut ctx
2292        );
2293        let doubly_sliced = sliced.slice(35..36, &mut ctx).unwrap().unwrap();
2294        assert_eq!(doubly_sliced.array_len(), 1);
2295        assert_eq!(doubly_sliced.offset(), 50);
2296        assert_eq!(
2297            doubly_sliced.search_index(0, &mut ctx).unwrap(),
2298            SearchResult::Found(0)
2299        );
2300        assert_arrays_eq!(
2301            doubly_sliced.values(),
2302            PrimitiveArray::from_iter([13531u32]),
2303            &mut ctx
2304        );
2305    }
2306
2307    #[test]
2308    fn test_mask_all_true() {
2309        let mut ctx = SESSION.create_execution_ctx();
2310        let patches = Patches::new(
2311            10,
2312            0,
2313            buffer![2u64, 5, 8].into_array(),
2314            buffer![100i32, 200, 300].into_array(),
2315            None,
2316            &mut ctx,
2317        )
2318        .unwrap();
2319
2320        let mask = Mask::new_true(10);
2321        let masked = patches.mask(&mask, &mut ctx).unwrap();
2322        assert!(masked.is_none());
2323    }
2324
2325    #[test]
2326    fn test_mask_all_false() {
2327        let mut ctx = SESSION.create_execution_ctx();
2328        let patches = Patches::new(
2329            10,
2330            0,
2331            buffer![2u64, 5, 8].into_array(),
2332            buffer![100i32, 200, 300].into_array(),
2333            None,
2334            &mut ctx,
2335        )
2336        .unwrap();
2337
2338        let mask = Mask::new_false(10);
2339        let masked = patches.mask(&mask, &mut ctx).unwrap().unwrap();
2340
2341        // Masking widens the surviving (still valid) values to nullable.
2342        assert!(masked.values().dtype().is_nullable());
2343        assert_arrays_eq!(
2344            masked.values(),
2345            PrimitiveArray::from_option_iter([Some(100i32), Some(200), Some(300)]),
2346            &mut ctx
2347        );
2348        assert!(masked.values().is_valid(0, &mut ctx).unwrap());
2349        assert!(masked.values().is_valid(1, &mut ctx).unwrap());
2350        assert!(masked.values().is_valid(2, &mut ctx).unwrap());
2351
2352        // Indices should remain unchanged
2353        assert_arrays_eq!(
2354            masked.indices(),
2355            PrimitiveArray::from_iter([2u64, 5, 8]),
2356            &mut ctx
2357        );
2358    }
2359
2360    #[test]
2361    fn test_mask_partial() {
2362        let mut ctx = SESSION.create_execution_ctx();
2363        let patches = Patches::new(
2364            10,
2365            0,
2366            buffer![2u64, 5, 8].into_array(),
2367            buffer![100i32, 200, 300].into_array(),
2368            None,
2369            &mut ctx,
2370        )
2371        .unwrap();
2372
2373        // Mask that removes patches at indices 2 and 8 (but not 5)
2374        let mask = Mask::from_iter([
2375            false, false, true, false, false, false, false, false, true, false,
2376        ]);
2377        let masked = patches.mask(&mask, &mut ctx).unwrap().unwrap();
2378
2379        // Only the patch at index 5 should remain
2380        assert_eq!(masked.values().len(), 1);
2381        assert_arrays_eq!(
2382            masked.values(),
2383            PrimitiveArray::from_option_iter([Some(200i32)]),
2384            &mut ctx
2385        );
2386
2387        // Only index 5 should remain
2388        assert_arrays_eq!(
2389            masked.indices(),
2390            PrimitiveArray::from_iter([5u64]),
2391            &mut ctx
2392        );
2393    }
2394
2395    #[test]
2396    fn test_mask_with_offset() {
2397        let mut ctx = SESSION.create_execution_ctx();
2398        let patches = Patches::new(
2399            10,
2400            5,                                  // offset
2401            buffer![7u64, 10, 13].into_array(), // actual indices are 2, 5, 8
2402            buffer![100i32, 200, 300].into_array(),
2403            None,
2404            &mut ctx,
2405        )
2406        .unwrap();
2407
2408        // Mask that sets actual index 2 to null
2409        let mask = Mask::from_iter([
2410            false, false, true, false, false, false, false, false, false, false,
2411        ]);
2412
2413        let masked = patches.mask(&mask, &mut ctx).unwrap().unwrap();
2414        assert_eq!(masked.array_len(), 10);
2415        assert_eq!(masked.offset(), 5);
2416        assert_arrays_eq!(
2417            masked.indices(),
2418            PrimitiveArray::from_iter([10u64, 13]),
2419            &mut ctx
2420        );
2421        assert_arrays_eq!(
2422            masked.values(),
2423            PrimitiveArray::from_option_iter([Some(200i32), Some(300)]),
2424            &mut ctx
2425        );
2426    }
2427
2428    #[test]
2429    fn test_mask_nullable_values() {
2430        let mut ctx = SESSION.create_execution_ctx();
2431        let patches = Patches::new(
2432            10,
2433            0,
2434            buffer![2u64, 5, 8].into_array(),
2435            PrimitiveArray::from_option_iter([Some(100i32), None, Some(300)]).into_array(),
2436            None,
2437            &mut ctx,
2438        )
2439        .unwrap();
2440
2441        // Test masking removes patch at index 2
2442        let mask = Mask::from_iter([
2443            false, false, true, false, false, false, false, false, false, false,
2444        ]);
2445        let masked = patches.mask(&mask, &mut ctx).unwrap().unwrap();
2446
2447        // Patches at indices 5 and 8 should remain
2448        assert_arrays_eq!(
2449            masked.indices(),
2450            PrimitiveArray::from_iter([5u64, 8]),
2451            &mut ctx
2452        );
2453
2454        // Values should be the null and 300
2455        let masked_values = masked
2456            .values()
2457            .clone()
2458            .execute::<PrimitiveArray>(&mut ctx)
2459            .unwrap();
2460        assert_eq!(masked_values.len(), 2);
2461        assert!(!masked_values.is_valid(0, &mut ctx).unwrap()); // the null value at index 5
2462        assert!(masked_values.is_valid(1, &mut ctx).unwrap()); // the 300 value at index 8
2463        assert_eq!(
2464            i32::try_from(&masked_values.execute_scalar(1, &mut ctx).unwrap()).unwrap(),
2465            300i32
2466        );
2467    }
2468
2469    /// Covers each filter algorithm.
2470    #[rstest]
2471    #[case::sparse_mask((0..1000).step_by(2).collect(), (0..1000).step_by(97).collect())]
2472    #[case::sparse_patches((0..1000).step_by(97).collect(), (0..1000).step_by(2).collect())]
2473    #[case::very_sparse_patches(vec![2, 998], (0..1000).step_by(2).collect())]
2474    #[case::similar_sizes((0..1000).step_by(3).collect(), (0..1000).step_by(2).collect())]
2475    #[case::moderately_sparse_mask((0..1000).step_by(2).collect(), (0..1000).step_by(17).collect())]
2476    #[case::no_overlap((0..500).collect(), (500..1000).step_by(50).collect())]
2477    #[case::no_overlap_sparse_patches((500..1000).step_by(100).collect(), (0..500).collect())]
2478    #[case::edges(vec![0, 1, 998, 999], vec![0, 999])]
2479    #[case::sparse_cached_mask_late_match((0..1000).step_by(100).collect(), vec![3, 900])]
2480    #[case::all_patches_kept((0..1000).step_by(100).collect(), (0..1000).step_by(2).collect())]
2481    fn test_filter_matches_naive(
2482        #[case] patch_indices: Vec<usize>,
2483        #[case] mask_indices: Vec<usize>,
2484        #[values(0, 5)] offset: usize,
2485        #[values(true, false)] cache_mask_indices: bool,
2486        #[values(0, 3)] mask_offset: usize,
2487    ) -> VortexResult<()> {
2488        const LEN: usize = 1000;
2489        let mut ctx = SESSION.create_execution_ctx();
2490
2491        let patches = Patches::new(
2492            LEN,
2493            offset,
2494            patch_indices
2495                .iter()
2496                .map(|&index| u32::try_from(index + offset).vortex_expect("index fits in u32"))
2497                .collect::<Buffer<u32>>()
2498                .into_array(),
2499            (0i32..)
2500                .take(patch_indices.len())
2501                .collect::<Buffer<i32>>()
2502                .into_array(),
2503            None,
2504            &mut ctx,
2505        )?;
2506
2507        let mask = if cache_mask_indices && mask_offset == 0 {
2508            Mask::from_indices(LEN, mask_indices.iter().copied())
2509        } else {
2510            let bits = BitBuffer::from_iter((0..LEN + mask_offset).map(|index| {
2511                index >= mask_offset && mask_indices.binary_search(&(index - mask_offset)).is_ok()
2512            }));
2513            let mask = Mask::from_buffer(bits.slice(mask_offset..));
2514            if cache_mask_indices {
2515                mask.values().vortex_expect("partial mask").indices();
2516            }
2517            mask
2518        };
2519
2520        let (expected_indices, expected_values): (Vec<u64>, Vec<i32>) = mask_indices
2521            .iter()
2522            .enumerate()
2523            .filter_map(|(mask_position, index)| {
2524                patch_indices
2525                    .binary_search(index)
2526                    .ok()
2527                    .map(|patch_position| {
2528                        (
2529                            mask_position as u64,
2530                            i32::try_from(patch_position).vortex_expect("position fits in i32"),
2531                        )
2532                    })
2533            })
2534            .unzip();
2535
2536        let filtered = patches.filter(&mask, &mut ctx)?;
2537
2538        let Some(filtered) = filtered else {
2539            assert!(expected_indices.is_empty());
2540            return Ok(());
2541        };
2542
2543        assert_eq!(filtered.array_len(), mask_indices.len());
2544        assert_arrays_eq!(
2545            filtered.indices(),
2546            PrimitiveArray::from_iter(expected_indices),
2547            &mut ctx
2548        );
2549        assert_arrays_eq!(
2550            filtered.values(),
2551            PrimitiveArray::from_iter(expected_values),
2552            &mut ctx
2553        );
2554
2555        Ok(())
2556    }
2557
2558    /// Mask indices past the maximum of the patch index type cannot match a patch.
2559    #[test]
2560    fn test_filter_sparse_mask_past_index_type_max() -> VortexResult<()> {
2561        let mut ctx = SESSION.create_execution_ctx();
2562        let patches = Patches::new(
2563            1000,
2564            0,
2565            (0..=u8::MAX).collect::<Buffer<u8>>().into_array(),
2566            (0..256i32).collect::<Buffer<i32>>().into_array(),
2567            None,
2568            &mut ctx,
2569        )?;
2570
2571        let mask = Mask::from_indices(1000, [3, 255, 256, 900]);
2572        let filtered = patches
2573            .filter(&mask, &mut ctx)?
2574            .expect("patches at 3 and 255 are kept");
2575
2576        assert_arrays_eq!(
2577            filtered.indices(),
2578            PrimitiveArray::from_iter([0u64, 1]),
2579            &mut ctx
2580        );
2581        assert_arrays_eq!(
2582            filtered.values(),
2583            PrimitiveArray::from_iter([3i32, 255]),
2584            &mut ctx
2585        );
2586
2587        Ok(())
2588    }
2589
2590    #[test]
2591    fn test_filter_keep_all() {
2592        let mut ctx = SESSION.create_execution_ctx();
2593        let patches = Patches::new(
2594            10,
2595            0,
2596            buffer![2u64, 5, 8].into_array(),
2597            buffer![100i32, 200, 300].into_array(),
2598            None,
2599            &mut ctx,
2600        )
2601        .unwrap();
2602
2603        // Keep all indices (mask with indices 0-9)
2604        let mask = Mask::from_indices(10, 0..10);
2605        let filtered = patches.filter(&mask, &mut ctx).unwrap().unwrap();
2606
2607        assert_arrays_eq!(
2608            filtered.indices(),
2609            PrimitiveArray::from_iter([2u64, 5, 8]),
2610            &mut ctx
2611        );
2612        assert_arrays_eq!(
2613            filtered.values(),
2614            PrimitiveArray::from_iter([100i32, 200, 300]),
2615            &mut ctx
2616        );
2617    }
2618
2619    #[test]
2620    fn test_filter_none() {
2621        let mut ctx = SESSION.create_execution_ctx();
2622        let patches = Patches::new(
2623            10,
2624            0,
2625            buffer![2u64, 5, 8].into_array(),
2626            buffer![100i32, 200, 300].into_array(),
2627            None,
2628            &mut ctx,
2629        )
2630        .unwrap();
2631
2632        // Filter out all (empty mask means keep nothing)
2633        let mask = Mask::from_indices(10, vec![]);
2634        let filtered = patches.filter(&mask, &mut ctx).unwrap();
2635        assert!(filtered.is_none());
2636    }
2637
2638    #[test]
2639    fn test_filter_with_indices() {
2640        let mut ctx = SESSION.create_execution_ctx();
2641        let patches = Patches::new(
2642            10,
2643            0,
2644            buffer![2u64, 5, 8].into_array(),
2645            buffer![100i32, 200, 300].into_array(),
2646            None,
2647            &mut ctx,
2648        )
2649        .unwrap();
2650
2651        // Keep indices 2, 5, 9 (so patches at 2 and 5 remain)
2652        let mask = Mask::from_indices(10, vec![2, 5, 9]);
2653        let filtered = patches.filter(&mask, &mut ctx).unwrap().unwrap();
2654
2655        assert_arrays_eq!(
2656            filtered.indices(),
2657            PrimitiveArray::from_iter([0u64, 1]),
2658            &mut ctx
2659        ); // Adjusted indices
2660        assert_arrays_eq!(
2661            filtered.values(),
2662            PrimitiveArray::from_iter([100i32, 200]),
2663            &mut ctx
2664        );
2665    }
2666
2667    #[test]
2668    fn test_slice_full_range() {
2669        let mut ctx = SESSION.create_execution_ctx();
2670        let patches = Patches::new(
2671            10,
2672            0,
2673            buffer![2u64, 5, 8].into_array(),
2674            buffer![100i32, 200, 300].into_array(),
2675            None,
2676            &mut ctx,
2677        )
2678        .unwrap();
2679
2680        let sliced = patches.slice(0..10, &mut ctx).unwrap().unwrap();
2681
2682        assert_arrays_eq!(
2683            sliced.indices(),
2684            PrimitiveArray::from_iter([2u64, 5, 8]),
2685            &mut ctx
2686        );
2687        assert_arrays_eq!(
2688            sliced.values(),
2689            PrimitiveArray::from_iter([100i32, 200, 300]),
2690            &mut ctx
2691        );
2692    }
2693
2694    #[test]
2695    fn test_slice_partial() {
2696        let mut ctx = SESSION.create_execution_ctx();
2697        let patches = Patches::new(
2698            10,
2699            0,
2700            buffer![2u64, 5, 8].into_array(),
2701            buffer![100i32, 200, 300].into_array(),
2702            None,
2703            &mut ctx,
2704        )
2705        .unwrap();
2706
2707        // Slice from 3 to 8 (includes patch at 5)
2708        let sliced = patches.slice(3..8, &mut ctx).unwrap().unwrap();
2709
2710        assert_arrays_eq!(
2711            sliced.indices(),
2712            PrimitiveArray::from_iter([5u64]),
2713            &mut ctx
2714        ); // Index stays the same
2715        assert_arrays_eq!(
2716            sliced.values(),
2717            PrimitiveArray::from_iter([200i32]),
2718            &mut ctx
2719        );
2720        assert_eq!(sliced.array_len(), 5); // 8 - 3 = 5
2721        assert_eq!(sliced.offset(), 3); // New offset
2722    }
2723
2724    #[test]
2725    fn test_slice_no_patches() {
2726        let mut ctx = SESSION.create_execution_ctx();
2727        let patches = Patches::new(
2728            10,
2729            0,
2730            buffer![2u64, 5, 8].into_array(),
2731            buffer![100i32, 200, 300].into_array(),
2732            None,
2733            &mut ctx,
2734        )
2735        .unwrap();
2736
2737        // Slice from 6 to 7 (no patches in this range)
2738        let sliced = patches.slice(6..7, &mut ctx).unwrap();
2739        assert!(sliced.is_none());
2740    }
2741
2742    #[test]
2743    fn test_slice_with_offset() {
2744        let mut ctx = SESSION.create_execution_ctx();
2745        let patches = Patches::new(
2746            10,
2747            5,                                  // offset
2748            buffer![7u64, 10, 13].into_array(), // actual indices are 2, 5, 8
2749            buffer![100i32, 200, 300].into_array(),
2750            None,
2751            &mut ctx,
2752        )
2753        .unwrap();
2754
2755        // Slice from 3 to 8 (includes patch at actual index 5)
2756        let sliced = patches.slice(3..8, &mut ctx).unwrap().unwrap();
2757
2758        assert_arrays_eq!(
2759            sliced.indices(),
2760            PrimitiveArray::from_iter([10u64]),
2761            &mut ctx
2762        ); // Index stays the same (offset + 5 = 10)
2763        assert_arrays_eq!(
2764            sliced.values(),
2765            PrimitiveArray::from_iter([200i32]),
2766            &mut ctx
2767        );
2768        assert_eq!(sliced.offset(), 8); // New offset = 5 + 3
2769    }
2770
2771    #[test]
2772    fn test_indices_range() {
2773        let mut ctx = SESSION.create_execution_ctx();
2774        let patches = Patches::new(
2775            10,
2776            0,
2777            buffer![2u64, 5, 8].into_array(),
2778            buffer![100i32, 200, 300].into_array(),
2779            None,
2780            &mut ctx,
2781        )
2782        .unwrap();
2783
2784        assert_eq!(patches.min_index(&mut ctx).unwrap(), 2);
2785        assert_eq!(patches.max_index(&mut ctx).unwrap(), 8);
2786    }
2787
2788    #[test]
2789    fn test_search_index() {
2790        let mut ctx = SESSION.create_execution_ctx();
2791        let patches = Patches::new(
2792            10,
2793            0,
2794            buffer![2u64, 5, 8].into_array(),
2795            buffer![100i32, 200, 300].into_array(),
2796            None,
2797            &mut ctx,
2798        )
2799        .unwrap();
2800
2801        // Search for exact indices
2802        assert_eq!(
2803            patches.search_index(2, &mut ctx).unwrap(),
2804            SearchResult::Found(0)
2805        );
2806        assert_eq!(
2807            patches.search_index(5, &mut ctx).unwrap(),
2808            SearchResult::Found(1)
2809        );
2810        assert_eq!(
2811            patches.search_index(8, &mut ctx).unwrap(),
2812            SearchResult::Found(2)
2813        );
2814
2815        // Search for non-patch indices
2816        assert_eq!(
2817            patches.search_index(0, &mut ctx).unwrap(),
2818            SearchResult::NotFound(0)
2819        );
2820        assert_eq!(
2821            patches.search_index(3, &mut ctx).unwrap(),
2822            SearchResult::NotFound(1)
2823        );
2824        assert_eq!(
2825            patches.search_index(6, &mut ctx).unwrap(),
2826            SearchResult::NotFound(2)
2827        );
2828        assert_eq!(
2829            patches.search_index(9, &mut ctx).unwrap(),
2830            SearchResult::NotFound(3)
2831        );
2832    }
2833
2834    #[test]
2835    fn test_mask_boundary_patches() {
2836        let mut ctx = SESSION.create_execution_ctx();
2837        // Test masking patches at array boundaries
2838        let patches = Patches::new(
2839            10,
2840            0,
2841            buffer![0u64, 9].into_array(),
2842            buffer![100i32, 200].into_array(),
2843            None,
2844            &mut ctx,
2845        )
2846        .unwrap();
2847
2848        let mask = Mask::from_iter([
2849            true, false, false, false, false, false, false, false, false, false,
2850        ]);
2851        let masked = patches.mask(&mask, &mut ctx).unwrap();
2852        assert!(masked.is_some());
2853        let masked = masked.unwrap();
2854        assert_arrays_eq!(
2855            masked.indices(),
2856            PrimitiveArray::from_iter([9u64]),
2857            &mut ctx
2858        );
2859        assert_arrays_eq!(
2860            masked.values(),
2861            PrimitiveArray::from_option_iter([Some(200i32)]),
2862            &mut ctx
2863        );
2864    }
2865
2866    #[test]
2867    fn test_mask_all_patches_removed() {
2868        let mut ctx = SESSION.create_execution_ctx();
2869        // Test when all patches are masked out
2870        let patches = Patches::new(
2871            10,
2872            0,
2873            buffer![2u64, 5, 8].into_array(),
2874            buffer![100i32, 200, 300].into_array(),
2875            None,
2876            &mut ctx,
2877        )
2878        .unwrap();
2879
2880        // Mask that removes all patches
2881        let mask = Mask::from_iter([
2882            false, false, true, false, false, true, false, false, true, false,
2883        ]);
2884        let masked = patches.mask(&mask, &mut ctx).unwrap();
2885        assert!(masked.is_none());
2886    }
2887
2888    #[test]
2889    fn test_mask_no_patches_removed() {
2890        let mut ctx = SESSION.create_execution_ctx();
2891        // Test when no patches are masked
2892        let patches = Patches::new(
2893            10,
2894            0,
2895            buffer![2u64, 5, 8].into_array(),
2896            buffer![100i32, 200, 300].into_array(),
2897            None,
2898            &mut ctx,
2899        )
2900        .unwrap();
2901
2902        // Mask that doesn't affect any patches
2903        let mask = Mask::from_iter([
2904            true, false, false, true, false, false, true, false, false, true,
2905        ]);
2906        let masked = patches.mask(&mask, &mut ctx).unwrap().unwrap();
2907
2908        assert_arrays_eq!(
2909            masked.indices(),
2910            PrimitiveArray::from_iter([2u64, 5, 8]),
2911            &mut ctx
2912        );
2913        assert_arrays_eq!(
2914            masked.values(),
2915            PrimitiveArray::from_option_iter([Some(100i32), Some(200), Some(300)]),
2916            &mut ctx
2917        );
2918    }
2919
2920    #[test]
2921    fn test_mask_single_patch() {
2922        let mut ctx = SESSION.create_execution_ctx();
2923        // Test with a single patch
2924        let patches = Patches::new(
2925            5,
2926            0,
2927            buffer![2u64].into_array(),
2928            buffer![42i32].into_array(),
2929            None,
2930            &mut ctx,
2931        )
2932        .unwrap();
2933
2934        // Mask that removes the single patch
2935        let mask = Mask::from_iter([false, false, true, false, false]);
2936        let masked = patches.mask(&mask, &mut ctx).unwrap();
2937        assert!(masked.is_none());
2938
2939        // Mask that keeps the single patch
2940        let mask = Mask::from_iter([true, false, false, true, false]);
2941        let masked = patches.mask(&mask, &mut ctx).unwrap().unwrap();
2942        assert_arrays_eq!(
2943            masked.indices(),
2944            PrimitiveArray::from_iter([2u64]),
2945            &mut ctx
2946        );
2947        assert_arrays_eq!(
2948            masked.values(),
2949            PrimitiveArray::from_option_iter([Some(42i32)]),
2950            &mut ctx
2951        );
2952    }
2953
2954    #[test]
2955    fn test_mask_contiguous_patches() {
2956        let mut ctx = SESSION.create_execution_ctx();
2957        // Test with contiguous patches
2958        let patches = Patches::new(
2959            10,
2960            0,
2961            buffer![3u64, 4, 5, 6].into_array(),
2962            buffer![100i32, 200, 300, 400].into_array(),
2963            None,
2964            &mut ctx,
2965        )
2966        .unwrap();
2967
2968        // Mask that removes middle patches
2969        let mask = Mask::from_iter([
2970            false, false, false, false, true, true, false, false, false, false,
2971        ]);
2972        let masked = patches.mask(&mask, &mut ctx).unwrap().unwrap();
2973
2974        assert_arrays_eq!(
2975            masked.indices(),
2976            PrimitiveArray::from_iter([3u64, 6]),
2977            &mut ctx
2978        );
2979        assert_arrays_eq!(
2980            masked.values(),
2981            PrimitiveArray::from_option_iter([Some(100i32), Some(400)]),
2982            &mut ctx
2983        );
2984    }
2985
2986    #[test]
2987    fn test_mask_with_large_offset() {
2988        let mut ctx = SESSION.create_execution_ctx();
2989        // Test with a large offset that shifts all indices
2990        let patches = Patches::new(
2991            20,
2992            15,
2993            buffer![16u64, 17, 19].into_array(), // actual indices are 1, 2, 4
2994            buffer![100i32, 200, 300].into_array(),
2995            None,
2996            &mut ctx,
2997        )
2998        .unwrap();
2999
3000        // Mask that removes the patch at actual index 2
3001        let mask = Mask::from_iter([
3002            false, false, true, false, false, false, false, false, false, false, false, false,
3003            false, false, false, false, false, false, false, false,
3004        ]);
3005        let masked = patches.mask(&mask, &mut ctx).unwrap().unwrap();
3006
3007        assert_arrays_eq!(
3008            masked.indices(),
3009            PrimitiveArray::from_iter([16u64, 19]),
3010            &mut ctx
3011        );
3012        assert_arrays_eq!(
3013            masked.values(),
3014            PrimitiveArray::from_option_iter([Some(100i32), Some(300)]),
3015            &mut ctx
3016        );
3017    }
3018
3019    #[test]
3020    #[should_panic(expected = "Filter mask length 5 does not match array length 10")]
3021    fn test_mask_wrong_length() {
3022        let mut ctx = SESSION.create_execution_ctx();
3023        let patches = Patches::new(
3024            10,
3025            0,
3026            buffer![2u64, 5, 8].into_array(),
3027            buffer![100i32, 200, 300].into_array(),
3028            None,
3029            &mut ctx,
3030        )
3031        .unwrap();
3032
3033        // Mask with wrong length
3034        let mask = Mask::from_iter([false, false, true, false, false]);
3035        patches.mask(&mask, &mut ctx).unwrap();
3036    }
3037
3038    #[test]
3039    fn test_chunk_offsets_search() {
3040        let mut ctx = SESSION.create_execution_ctx();
3041        let indices = buffer![100u64, 200, 3000, 3100].into_array();
3042        let values = buffer![10i32, 20, 30, 40].into_array();
3043        let chunk_offsets = buffer![0u64, 2, 2, 3].into_array();
3044        let patches =
3045            Patches::new(4096, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3046
3047        assert!(patches.chunk_offsets.is_some());
3048
3049        // chunk 0: patches at 100, 200
3050        assert_eq!(
3051            patches.search_index(100, &mut ctx).unwrap(),
3052            SearchResult::Found(0)
3053        );
3054        assert_eq!(
3055            patches.search_index(200, &mut ctx).unwrap(),
3056            SearchResult::Found(1)
3057        );
3058
3059        // Chunk 1 has no patches; 2000 is before the first patch in chunk 2.
3060        assert_eq!(
3061            patches.search_index(1500, &mut ctx).unwrap(),
3062            SearchResult::NotFound(2)
3063        );
3064        assert_eq!(
3065            patches.search_index(2000, &mut ctx).unwrap(),
3066            SearchResult::NotFound(2)
3067        );
3068
3069        // The patches at 3000 and 3100 straddle chunks 2 and 3.
3070        assert_eq!(
3071            patches.search_index(3000, &mut ctx).unwrap(),
3072            SearchResult::Found(2)
3073        );
3074        assert_eq!(
3075            patches.search_index(3100, &mut ctx).unwrap(),
3076            SearchResult::Found(3)
3077        );
3078
3079        assert_eq!(
3080            patches.search_index(1024, &mut ctx).unwrap(),
3081            SearchResult::NotFound(2)
3082        );
3083    }
3084
3085    #[test]
3086    fn test_chunk_offsets_with_slice() {
3087        let mut ctx = SESSION.create_execution_ctx();
3088        let indices = buffer![100u64, 500, 1200, 1300, 1500, 1800, 2100, 2500].into_array();
3089        let values = buffer![10i32, 20, 30, 35, 40, 45, 50, 60].into_array();
3090        let chunk_offsets = buffer![0u64, 2, 6].into_array();
3091        let patches =
3092            Patches::new(3000, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3093
3094        let sliced = patches.slice(1000..2200, &mut ctx).unwrap().unwrap();
3095
3096        assert!(sliced.chunk_offsets.is_some());
3097        assert_eq!(sliced.offset(), 1000);
3098
3099        assert_eq!(
3100            sliced.search_index(200, &mut ctx).unwrap(),
3101            SearchResult::Found(0)
3102        );
3103        assert_eq!(
3104            sliced.search_index(500, &mut ctx).unwrap(),
3105            SearchResult::Found(2)
3106        );
3107        assert_eq!(
3108            sliced.search_index(1100, &mut ctx).unwrap(),
3109            SearchResult::Found(4)
3110        );
3111
3112        assert_eq!(
3113            sliced.search_index(250, &mut ctx).unwrap(),
3114            SearchResult::NotFound(1)
3115        );
3116        assert_arrays_eq!(
3117            sliced.values(),
3118            PrimitiveArray::from_iter([30i32, 35, 40, 45, 50]),
3119            &mut ctx
3120        );
3121    }
3122
3123    #[test]
3124    fn test_chunk_offsets_with_slice_after_first_chunk() {
3125        let mut ctx = SESSION.create_execution_ctx();
3126        let indices = buffer![100u64, 500, 1200, 1300, 1500, 1800, 2100, 2500].into_array();
3127        let values = buffer![10i32, 20, 30, 35, 40, 45, 50, 60].into_array();
3128        let chunk_offsets = buffer![0u64, 2, 6].into_array();
3129        let patches =
3130            Patches::new(3000, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3131
3132        let sliced = patches.slice(1300..2200, &mut ctx).unwrap().unwrap();
3133
3134        assert!(sliced.chunk_offsets.is_some());
3135        assert_eq!(sliced.offset(), 1300);
3136
3137        assert_eq!(
3138            sliced.search_index(0, &mut ctx).unwrap(),
3139            SearchResult::Found(0)
3140        );
3141        assert_eq!(
3142            sliced.search_index(200, &mut ctx).unwrap(),
3143            SearchResult::Found(1)
3144        );
3145        assert_eq!(
3146            sliced.search_index(500, &mut ctx).unwrap(),
3147            SearchResult::Found(2)
3148        );
3149        assert_eq!(
3150            sliced.search_index(250, &mut ctx).unwrap(),
3151            SearchResult::NotFound(2)
3152        );
3153        assert_eq!(
3154            sliced.search_index(900, &mut ctx).unwrap(),
3155            SearchResult::NotFound(4)
3156        );
3157        assert_arrays_eq!(
3158            sliced.values(),
3159            PrimitiveArray::from_iter([35i32, 40, 45, 50]),
3160            &mut ctx
3161        );
3162    }
3163
3164    #[test]
3165    fn test_chunk_offsets_slice_empty_result() {
3166        let mut ctx = SESSION.create_execution_ctx();
3167        let indices = buffer![100u64, 200, 3000, 3100].into_array();
3168        let values = buffer![10i32, 20, 30, 40].into_array();
3169        let chunk_offsets = buffer![0u64, 2, 2, 3].into_array();
3170        let patches =
3171            Patches::new(4000, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3172
3173        let sliced = patches.slice(1000..2000, &mut ctx).unwrap();
3174        assert!(sliced.is_none());
3175    }
3176
3177    #[test]
3178    fn test_chunk_offsets_slice_single_patch() {
3179        let mut ctx = SESSION.create_execution_ctx();
3180        let indices = buffer![100u64, 1200, 1300, 2500].into_array();
3181        let values = buffer![10i32, 20, 30, 40].into_array();
3182        let chunk_offsets = buffer![0u64, 1, 3].into_array();
3183        let patches =
3184            Patches::new(3000, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3185
3186        let sliced = patches.slice(1100..1250, &mut ctx).unwrap().unwrap();
3187
3188        assert_eq!(sliced.num_patches(), 1);
3189        assert_eq!(sliced.offset(), 1100);
3190        assert_eq!(
3191            sliced.search_index(100, &mut ctx).unwrap(),
3192            SearchResult::Found(0)
3193        ); // 1200 - 1100 = 100
3194        assert_eq!(
3195            sliced.search_index(50, &mut ctx).unwrap(),
3196            SearchResult::NotFound(0)
3197        );
3198        assert_eq!(
3199            sliced.search_index(150, &mut ctx).unwrap(),
3200            SearchResult::NotFound(1)
3201        );
3202        assert_arrays_eq!(
3203            sliced.values(),
3204            PrimitiveArray::from_iter([20i32]),
3205            &mut ctx
3206        );
3207    }
3208
3209    #[test]
3210    fn test_chunk_offsets_slice_across_chunks() {
3211        let mut ctx = SESSION.create_execution_ctx();
3212        let indices = buffer![100u64, 200, 1100, 1200, 2100, 2200].into_array();
3213        let values = buffer![10i32, 20, 30, 40, 50, 60].into_array();
3214        let chunk_offsets = buffer![0u64, 2, 4].into_array();
3215        let patches =
3216            Patches::new(3000, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3217
3218        let sliced = patches.slice(150..2150, &mut ctx).unwrap().unwrap();
3219
3220        assert_eq!(sliced.num_patches(), 4);
3221        assert_eq!(sliced.offset(), 150);
3222
3223        assert_eq!(
3224            sliced.search_index(50, &mut ctx).unwrap(),
3225            SearchResult::Found(0)
3226        ); // 200 - 150 = 50
3227        assert_eq!(
3228            sliced.search_index(950, &mut ctx).unwrap(),
3229            SearchResult::Found(1)
3230        ); // 1100 - 150 = 950
3231        assert_eq!(
3232            sliced.search_index(1050, &mut ctx).unwrap(),
3233            SearchResult::Found(2)
3234        ); // 1200 - 150 = 1050
3235        assert_eq!(
3236            sliced.search_index(1950, &mut ctx).unwrap(),
3237            SearchResult::Found(3)
3238        ); // 2100 - 150 = 1950
3239        assert_arrays_eq!(
3240            sliced.values(),
3241            PrimitiveArray::from_iter([20i32, 30, 40, 50]),
3242            &mut ctx
3243        );
3244    }
3245
3246    #[test]
3247    fn test_chunk_offsets_boundary_searches() {
3248        let mut ctx = SESSION.create_execution_ctx();
3249        let indices = buffer![1023u64, 1024, 1025, 2047, 2048].into_array();
3250        let values = buffer![10i32, 20, 30, 40, 50].into_array();
3251        let chunk_offsets = buffer![0u64, 1, 4].into_array();
3252        let patches =
3253            Patches::new(3000, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3254
3255        assert_eq!(
3256            patches.search_index(1023, &mut ctx).unwrap(),
3257            SearchResult::Found(0)
3258        );
3259        assert_eq!(
3260            patches.search_index(1024, &mut ctx).unwrap(),
3261            SearchResult::Found(1)
3262        );
3263        assert_eq!(
3264            patches.search_index(1025, &mut ctx).unwrap(),
3265            SearchResult::Found(2)
3266        );
3267        assert_eq!(
3268            patches.search_index(2047, &mut ctx).unwrap(),
3269            SearchResult::Found(3)
3270        );
3271        assert_eq!(
3272            patches.search_index(2048, &mut ctx).unwrap(),
3273            SearchResult::Found(4)
3274        );
3275
3276        assert_eq!(
3277            patches.search_index(1022, &mut ctx).unwrap(),
3278            SearchResult::NotFound(0)
3279        );
3280        assert_eq!(
3281            patches.search_index(2046, &mut ctx).unwrap(),
3282            SearchResult::NotFound(3)
3283        );
3284    }
3285
3286    #[test]
3287    fn test_chunk_offsets_slice_edge_cases() {
3288        let mut ctx = SESSION.create_execution_ctx();
3289        let indices = buffer![0u64, 1, 1023, 1024, 2047, 2048].into_array();
3290        let values = buffer![10i32, 20, 30, 40, 50, 60].into_array();
3291        let chunk_offsets = buffer![0u64, 3, 5].into_array();
3292        let patches =
3293            Patches::new(3000, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3294
3295        // Slice at the very beginning
3296        let sliced = patches.slice(0..10, &mut ctx).unwrap().unwrap();
3297        assert_eq!(sliced.num_patches(), 2);
3298        assert_eq!(
3299            sliced.search_index(0, &mut ctx).unwrap(),
3300            SearchResult::Found(0)
3301        );
3302        assert_eq!(
3303            sliced.search_index(1, &mut ctx).unwrap(),
3304            SearchResult::Found(1)
3305        );
3306
3307        assert_arrays_eq!(
3308            sliced.values(),
3309            PrimitiveArray::from_iter([10i32, 20]),
3310            &mut ctx
3311        );
3312
3313        // Slice at the very end
3314        let sliced = patches.slice(2040..3000, &mut ctx).unwrap().unwrap();
3315        assert_eq!(sliced.num_patches(), 2); // patches at 2047 and 2048
3316        assert_eq!(
3317            sliced.search_index(7, &mut ctx).unwrap(),
3318            SearchResult::Found(0)
3319        ); // 2047 - 2040
3320        assert_eq!(
3321            sliced.search_index(8, &mut ctx).unwrap(),
3322            SearchResult::Found(1)
3323        ); // 2048 - 2040
3324        assert_arrays_eq!(
3325            sliced.values(),
3326            PrimitiveArray::from_iter([50i32, 60]),
3327            &mut ctx
3328        );
3329    }
3330
3331    #[test]
3332    fn test_chunk_offsets_slice_nested() {
3333        let mut ctx = SESSION.create_execution_ctx();
3334        let indices = buffer![100u64, 200, 300, 400, 500, 600].into_array();
3335        let values = buffer![10i32, 20, 30, 40, 50, 60].into_array();
3336        let chunk_offsets = buffer![0u64].into_array();
3337        let patches =
3338            Patches::new(1000, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3339
3340        let sliced1 = patches.slice(150..550, &mut ctx).unwrap().unwrap();
3341        assert_eq!(sliced1.num_patches(), 4); // 200, 300, 400, 500
3342
3343        let sliced2 = sliced1.slice(100..250, &mut ctx).unwrap().unwrap();
3344        assert_eq!(sliced2.num_patches(), 1); // 300
3345        assert_eq!(sliced2.offset(), 250);
3346
3347        assert_eq!(
3348            sliced2.search_index(50, &mut ctx).unwrap(),
3349            SearchResult::Found(0)
3350        ); // 300 - 250
3351        assert_eq!(
3352            sliced2.search_index(150, &mut ctx).unwrap(),
3353            SearchResult::NotFound(1)
3354        );
3355        assert_arrays_eq!(
3356            sliced1.values(),
3357            PrimitiveArray::from_iter([20i32, 30, 40, 50]),
3358            &mut ctx
3359        );
3360        assert_arrays_eq!(
3361            sliced2.values(),
3362            PrimitiveArray::from_iter([30i32]),
3363            &mut ctx
3364        );
3365    }
3366
3367    #[test]
3368    fn test_nested_slice_with_dropped_first_chunk() {
3369        let mut ctx = SESSION.create_execution_ctx();
3370        // PATCH_CHUNK_SIZE = 1024, so the two patches land in different chunks.
3371        let indices = buffer![0u64, 1024].into_array();
3372        let values = buffer![1i32, 2].into_array();
3373        let chunk_offsets = buffer![0u64, 1].into_array();
3374        let patches =
3375            Patches::new(2048, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3376
3377        // Drop chunk 0, then re-slice the result.
3378        let dropped_first = patches.slice(1024..2048, &mut ctx).unwrap().unwrap();
3379        let resliced = dropped_first.slice(0..1024, &mut ctx).unwrap().unwrap();
3380        assert_eq!(resliced.num_patches(), 1);
3381        assert_eq!(resliced.array_len(), 1024);
3382        assert_eq!(resliced.offset(), 1024);
3383        assert_eq!(
3384            resliced.search_index(0, &mut ctx).unwrap(),
3385            SearchResult::Found(0)
3386        );
3387        assert_arrays_eq!(
3388            resliced.values(),
3389            PrimitiveArray::from_iter([2i32]),
3390            &mut ctx
3391        );
3392    }
3393
3394    #[test]
3395    fn test_index_larger_than_length() {
3396        let mut ctx = SESSION.create_execution_ctx();
3397        let chunk_offsets = buffer![0u64].into_array();
3398        let indices = buffer![1023u64].into_array();
3399        let values = buffer![42i32].into_array();
3400        let patches =
3401            Patches::new(1024, 0, indices, values, Some(chunk_offsets), &mut ctx).unwrap();
3402        assert_eq!(
3403            patches.search_index(2048, &mut ctx).unwrap(),
3404            SearchResult::NotFound(1)
3405        );
3406    }
3407
3408    /// What a lookup into patches with corrupt chunk offsets does.
3409    #[derive(Clone, Copy, Debug)]
3410    enum CorruptOffsetLookup {
3411        SearchIndex,
3412        GetPatched,
3413        Take,
3414        Slice,
3415    }
3416
3417    /// Chunk offsets that can come from a corrupt file but that no writer produces.
3418    #[rstest]
3419    #[case::later_offset_below_the_first(buffer![2u64, 0, 0])]
3420    #[case::empty(Buffer::<u64>::empty())]
3421    #[case::fewer_than_the_chunks(buffer![0u64])]
3422    fn corrupt_chunk_offsets_return_errors(
3423        #[case] chunk_offsets: Buffer<u64>,
3424        #[values(
3425            CorruptOffsetLookup::SearchIndex,
3426            CorruptOffsetLookup::GetPatched,
3427            CorruptOffsetLookup::Take,
3428            CorruptOffsetLookup::Slice
3429        )]
3430        lookup: CorruptOffsetLookup,
3431    ) -> VortexResult<()> {
3432        let mut ctx = SESSION.create_execution_ctx();
3433        // Ten patches for one taken index, so `take` searches by chunk rather than through a map.
3434        let patches = Patches::new(
3435            3000,
3436            0,
3437            buffer![5u64, 100, 1500, 1600, 1700, 1800, 1900, 2100, 2500, 2999].into_array(),
3438            buffer![1i32, 2, 3, 4, 5, 6, 7, 8, 9, 10].into_array(),
3439            Some(chunk_offsets.into_array()),
3440            &mut ctx,
3441        )?;
3442        // The lookups land in the third chunk, which corrupt offsets describe wrongly or not at all.
3443        let result = match lookup {
3444            CorruptOffsetLookup::SearchIndex => patches.search_index(2100, &mut ctx).map(|_| ()),
3445            CorruptOffsetLookup::GetPatched => patches.get_patched(2100, &mut ctx).map(|_| ()),
3446            CorruptOffsetLookup::Take => patches
3447                .take(&buffer![2100u64].into_array(), &mut ctx)
3448                .map(|_| ()),
3449            CorruptOffsetLookup::Slice => patches.slice(2000..3000, &mut ctx).map(|_| ()),
3450        };
3451        assert!(
3452            result.is_err(),
3453            "{lookup:?} should reject corrupt chunk offsets"
3454        );
3455        Ok(())
3456    }
3457
3458    /// Builds piecewise indices, encoding uniform lengths or multipliers as constants.
3459    fn piecewise(starts: &[u64], lengths: &[u64], multipliers: &[u64]) -> ArrayRef {
3460        fn param(values: &[u64]) -> ArrayRef {
3461            match values.first() {
3462                Some(&first) if values.iter().all(|&v| v == first) => {
3463                    ConstantArray::new(first, values.len()).into_array()
3464                }
3465                _ => Buffer::copy_from(values).into_array(),
3466            }
3467        }
3468        let len =
3469            usize::try_from(lengths.iter().sum::<u64>()).vortex_expect("length fits in usize");
3470        PiecewiseSequenceArray::try_new(
3471            Buffer::copy_from(starts).into_array(),
3472            param(lengths),
3473            param(multipliers),
3474            len,
3475        )
3476        .vortex_expect("valid piecewise indices")
3477        .into_array()
3478    }
3479
3480    fn assert_take_piecewise_matches_materialized(
3481        patches: &Patches,
3482        indices: &ArrayRef,
3483    ) -> VortexResult<()> {
3484        let mut ctx = SESSION.create_execution_ctx();
3485        let materialized = indices.clone().execute::<PrimitiveArray>(&mut ctx)?;
3486        let expected = patches.take_search(materialized, false, &mut ctx)?;
3487        let actual = patches.take(indices, &mut ctx)?;
3488
3489        match (actual, expected) {
3490            (None, None) => {}
3491            (Some(actual), Some(expected)) => {
3492                assert_eq!(actual.array_len(), expected.array_len());
3493                assert_arrays_eq!(actual.indices(), expected.indices(), &mut ctx);
3494                assert_arrays_eq!(actual.values(), expected.values(), &mut ctx);
3495            }
3496            (actual, expected) => panic!(
3497                "expected {} patches, got {}",
3498                expected.map_or(0, |p| p.num_patches()),
3499                actual.map_or(0, |p| p.num_patches())
3500            ),
3501        }
3502        Ok(())
3503    }
3504
3505    #[rstest]
3506    #[case::contiguous(vec![0, 10, 30], vec![5, 8, 10], vec![1, 1, 1])]
3507    #[case::adjacent_runs(vec![4, 8], vec![4, 4], vec![1, 1])]
3508    #[case::repeated_runs(vec![2, 2], vec![6, 6], vec![1, 1])]
3509    #[case::descending(vec![30, 10, 0], vec![5, 8, 10], vec![1, 1, 1])]
3510    #[case::constant(vec![4, 5, 9], vec![3, 2, 1], vec![0, 0, 0])]
3511    #[case::strided(vec![0, 1], vec![20, 13], vec![2, 3])]
3512    #[case::sparse_stride(vec![4], vec![3], vec![13])]
3513    #[case::empty_pieces(vec![0, 9, 39], vec![0, 3, 1], vec![1, 1, 1])]
3514    #[case::no_matches(vec![0, 21], vec![2, 2], vec![1, 1])]
3515    #[case::out_of_bounds(vec![10, 40], vec![2, 5], vec![1, 1])]
3516    #[case::out_of_order_varied(vec![30, 0, 10], vec![5, 8, 2], vec![1, 1, 1])]
3517    // More pieces than patches, so the merge mostly gallops over the pieces.
3518    #[case::many_unit_pieces((0..42).step_by(2).collect(), vec![1; 21], vec![1; 21])]
3519    #[case::many_varied_pieces(
3520        (0..40).step_by(2).collect(),
3521        (0..20).map(|i| i % 3).collect(),
3522        vec![1; 20]
3523    )]
3524    #[case::many_overlapping_pieces((0..40).step_by(2).collect(), vec![3; 20], vec![1; 20])]
3525    #[case::many_descending_pieces((0..40).rev().step_by(2).collect(), vec![1; 20], vec![1; 20])]
3526    fn take_piecewise_matches_materialized(
3527        #[case] starts: Vec<u64>,
3528        #[case] lengths: Vec<u64>,
3529        #[case] multipliers: Vec<u64>,
3530    ) -> VortexResult<()> {
3531        let mut ctx = SESSION.create_execution_ctx();
3532        // Slicing gives the patches a non-zero offset.
3533        let patches = Patches::new(
3534            45,
3535            0,
3536            buffer![3u16, 4, 6, 9, 10, 11, 12, 13, 17, 30, 33, 41, 42, 44].into_array(),
3537            buffer![1i32, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14].into_array(),
3538            None,
3539            &mut ctx,
3540        )?
3541        .slice(2..44, &mut ctx)?
3542        .vortex_expect("sliced patches are non-empty");
3543
3544        assert_take_piecewise_matches_materialized(
3545            &patches,
3546            &piecewise(&starts, &lengths, &multipliers),
3547        )
3548    }
3549
3550    #[test]
3551    fn take_piecewise_long_runs_of_dense_patches() -> VortexResult<()> {
3552        let mut ctx = SESSION.create_execution_ctx();
3553        let patches = Patches::new(
3554            200,
3555            0,
3556            Buffer::from_iter(0u32..200).into_array(),
3557            Buffer::from_iter(0i64..200).into_array(),
3558            None,
3559            &mut ctx,
3560        )?;
3561        assert_take_piecewise_matches_materialized(
3562            &patches,
3563            &piecewise(&[5, 50, 120], &[30, 40, 20], &[1, 1, 1]),
3564        )
3565    }
3566}