arrow-select 60.2.0

Selection kernels for arrow arrays
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements

use crate::coalesce::{InProgressArray, append_gathered_nulls, check_filter_len};
use crate::filter::{FilterIndices, FilterPredicate, FilterSelection, FilterSlices};
use arrow_array::cast::AsArray;
use arrow_array::{Array, ArrayRef, ArrowPrimitiveType, PrimitiveArray, UInt32Array};
use arrow_buffer::{NullBuffer, NullBufferBuilder, ScalarBuffer};
use arrow_schema::{ArrowError, DataType};
use std::fmt::Debug;
use std::sync::Arc;

/// InProgressArray for [`PrimitiveArray`]
#[derive(Debug)]
pub(crate) struct InProgressPrimitiveArray<T: ArrowPrimitiveType> {
    /// Data type of the array
    data_type: DataType,
    /// The current source, if any
    source: Option<ArrayRef>,
    /// the target batch size (and thus size for views allocation)
    batch_size: usize,
    /// In progress nulls
    nulls: NullBufferBuilder,
    /// The currently in progress array
    current: Vec<T::Native>,
}

impl<T: ArrowPrimitiveType> InProgressPrimitiveArray<T> {
    /// Create a new `InProgressPrimitiveArray`
    pub(crate) fn new(batch_size: usize, data_type: DataType) -> Self {
        Self {
            data_type,
            batch_size,
            source: None,
            nulls: NullBufferBuilder::new(batch_size),
            current: vec![],
        }
    }

    /// Allocate space for output values if necessary.
    ///
    /// This is done on write (when we know it is necessary) rather than
    /// eagerly to avoid allocations that are not used.
    fn ensure_capacity(&mut self) {
        if self.current.capacity() == 0 {
            self.current.reserve(self.batch_size);
        }
    }

    /// # Safety
    ///
    /// Every index yielded by `indices` must be less than `values.len()`, and
    /// `indices` must yield exactly `selected_count` indices.
    unsafe fn append_values_by_indices(
        current: &mut Vec<T::Native>,
        values: &[T::Native],
        indices: FilterIndices<'_>,
        selected_count: usize,
    ) {
        current.reserve(selected_count);
        let current_len = current.len();
        let mut written = 0;

        // SAFETY: the caller guarantees that indices are in bounds and that
        // exactly `selected_count` values are written. Capacity was reserved
        // above.
        unsafe {
            let mut out = current
                .spare_capacity_mut()
                .as_mut_ptr()
                .cast::<T::Native>();

            indices.for_each(|idx| {
                out.write(*values.get_unchecked(idx));
                out = out.add(1);
                written += 1;
            });

            current.set_len(current_len + written);
        }

        debug_assert_eq!(written, selected_count);
    }

    /// # Safety
    ///
    /// Every range yielded by `slices` must satisfy
    /// `start <= end <= values.len()`, and the ranges must contain exactly
    /// `selected_count` values in total.
    unsafe fn append_values_by_slices(
        current: &mut Vec<T::Native>,
        values: &[T::Native],
        slices: FilterSlices<'_>,
        selected_count: usize,
    ) {
        current.reserve(selected_count);
        let current_len = current.len();
        let mut written = 0;

        // SAFETY: the caller guarantees that slices are in bounds and that
        // exactly `selected_count` values are written. Capacity was reserved
        // above.
        unsafe {
            let mut out = current
                .spare_capacity_mut()
                .as_mut_ptr()
                .cast::<T::Native>();

            slices.for_each(|(start, end)| {
                let len = end - start;
                std::ptr::copy_nonoverlapping(values.as_ptr().add(start), out, len);
                out = out.add(len);
                written += len;
            });

            current.set_len(current_len + written);
        }

        debug_assert_eq!(written, selected_count);
    }
}

#[inline]
fn primitive_source<T: ArrowPrimitiveType>(
    source: Option<&ArrayRef>,
) -> Result<&PrimitiveArray<T>, ArrowError> {
    Ok(source
        .ok_or_else(|| {
            ArrowError::InvalidArgumentError(
                "Internal Error: InProgressPrimitiveArray: source not set".to_string(),
            )
        })?
        .as_primitive::<T>())
}

fn append_filtered_nulls(
    nulls: &mut NullBufferBuilder,
    source_nulls: Option<&NullBuffer>,
    filter: &FilterPredicate,
) {
    if let Some(filtered_nulls) = filter.filter_nulls(source_nulls) {
        nulls.append_buffer(&filtered_nulls);
    } else {
        nulls.append_n_non_nulls(filter.count());
    }
}

impl<T: ArrowPrimitiveType + Debug> InProgressArray for InProgressPrimitiveArray<T> {
    fn set_source(&mut self, source: Option<ArrayRef>) {
        self.source = source;
    }

    fn copy_rows(&mut self, offset: usize, len: usize) -> Result<(), ArrowError> {
        self.ensure_capacity();

        let s = primitive_source::<T>(self.source.as_ref())?;

        // add nulls if necessary
        if let Some(nulls) = s.nulls().as_ref() {
            let nulls = nulls.slice(offset, len);
            self.nulls.append_buffer(&nulls);
        } else {
            self.nulls.append_n_non_nulls(len);
        }

        // Copy the values
        let values = s.values();
        self.current
            .extend_from_slice(&values[offset..offset + len]);

        Ok(())
    }

    fn copy_rows_by_filter(&mut self, filter: &FilterPredicate) -> Result<(), ArrowError> {
        let source_len = primitive_source::<T>(self.source.as_ref())?.len();
        check_filter_len(filter, source_len)?;

        match filter.selection() {
            FilterSelection::Indices(indices) => {
                self.ensure_capacity();
                let s = primitive_source::<T>(self.source.as_ref())?;

                append_filtered_nulls(&mut self.nulls, s.nulls(), filter);
                // SAFETY: `check_filter_len` verified the selected indices are
                // in bounds, and the filter yields `filter.count()` indices.
                unsafe {
                    Self::append_values_by_indices(
                        &mut self.current,
                        s.values(),
                        indices,
                        filter.count(),
                    )
                };
                Ok(())
            }
            FilterSelection::Slices(slices) => {
                self.ensure_capacity();
                let s = primitive_source::<T>(self.source.as_ref())?;

                append_filtered_nulls(&mut self.nulls, s.nulls(), filter);
                // SAFETY: `check_filter_len` verified the selected slices are
                // in bounds, and the filter yields `filter.count()` values.
                unsafe {
                    Self::append_values_by_slices(
                        &mut self.current,
                        s.values(),
                        slices,
                        filter.count(),
                    )
                };
                Ok(())
            }
            // Other selection shapes reuse the generic copy_rows path.
            selection => self.copy_rows_by_selection(selection),
        }
    }

    /// # Safety
    ///
    /// `indices` must not contain nulls, and every value must be less than
    /// `source.len()`.
    unsafe fn copy_rows_by_indices(
        &mut self,
        source: &ArrayRef,
        indices: &UInt32Array,
    ) -> Result<(), ArrowError> {
        if indices.is_empty() {
            return Ok(());
        }
        let typed = source.as_primitive::<T>();
        self.ensure_capacity();

        if let Some(src_nulls) = typed.nulls() {
            // SAFETY: the caller validated every index against `typed.len()`, which
            // equals the length of its null buffer.
            unsafe { append_gathered_nulls(&mut self.nulls, src_nulls, indices) };
        } else {
            self.nulls.append_n_non_nulls(indices.len());
        }

        let index_values = indices.values();
        let values = typed.values();
        let current_len = self.current.len();
        self.current.reserve(indices.len());
        debug_assert!(
            index_values
                .iter()
                .all(|&idx| (idx as usize) < values.len()),
            "copy_rows_by_indices requires caller-validated in-bounds indices",
        );
        // SAFETY: the caller guarantees every index is in bounds, and reserve
        // allocated one output slot per index.
        unsafe {
            let base = self
                .current
                .spare_capacity_mut()
                .as_mut_ptr()
                .cast::<T::Native>();
            let src = values.as_ptr();
            for (i, &idx) in index_values.iter().enumerate() {
                base.add(i).write(*src.add(idx as usize));
            }
            self.current.set_len(current_len + indices.len());
        }
        Ok(())
    }

    fn finish(&mut self) -> Result<ArrayRef, ArrowError> {
        // take and reset the current values and nulls
        let values = std::mem::take(&mut self.current);
        let nulls = self.nulls.finish();
        self.nulls = NullBufferBuilder::new(self.batch_size);

        let array = PrimitiveArray::<T>::try_new(ScalarBuffer::from(values), nulls)?
            // preserve timezone / precision+scale if applicable
            .with_data_type(self.data_type.clone());
        Ok(Arc::new(array))
    }

    fn size(&self) -> usize {
        self.source
            .as_ref()
            .map_or(0, |source| source.get_array_memory_size())
            + self.current.capacity() * std::mem::size_of::<T::Native>()
            + self.nulls.allocated_size()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::filter::FilterBuilder;
    use crate::take::take;
    use arrow_array::types::Int32Type;
    use arrow_array::{BooleanArray, Int32Array, UInt32Array};

    #[test]
    fn test_copy_rows_by_filter_index_iterator() {
        let source =
            Int32Array::from_iter((0..21).map(|idx| if idx % 5 == 0 { None } else { Some(idx) }));
        let filter = BooleanArray::from_iter(
            (0..21).map(|idx| Some(matches!(idx, 0 | 1 | 2 | 3 | 5 | 8 | 13))),
        );
        let predicate = FilterBuilder::new(&filter).build();
        let FilterSelection::Indices(indices) = predicate.selection() else {
            panic!("expected index iterator selection");
        };
        let mut selected_indices = Vec::new();
        indices.for_each(|idx| selected_indices.push(idx));
        assert_eq!(selected_indices, vec![0, 1, 2, 3, 5, 8, 13]);

        let mut in_progress = InProgressPrimitiveArray::<Int32Type>::new(7, DataType::Int32);
        in_progress.set_source(Some(Arc::new(source)));
        in_progress.copy_rows_by_filter(&predicate).unwrap();

        let result = in_progress.finish().unwrap();
        let result = result.as_primitive::<Int32Type>();
        let expected = Int32Array::from(vec![
            None,
            Some(1),
            Some(2),
            Some(3),
            None,
            Some(8),
            Some(13),
        ]);
        assert_eq!(result, &expected);
    }

    #[test]
    fn test_copy_rows_by_filter_slice_iterator() {
        let source =
            Int32Array::from_iter((0..16).map(|idx| if idx % 5 == 0 { None } else { Some(idx) }));
        let filter = BooleanArray::from_iter((0..16).map(|idx| Some(!matches!(idx, 3 | 9))));
        let predicate = FilterBuilder::new(&filter).build();
        let FilterSelection::Slices(slices) = predicate.selection() else {
            panic!("expected slice iterator selection");
        };
        let mut selected_slices = Vec::new();
        slices.for_each(|slice| selected_slices.push(slice));
        assert_eq!(selected_slices, vec![(0, 3), (4, 9), (10, 16)]);

        let mut in_progress = InProgressPrimitiveArray::<Int32Type>::new(14, DataType::Int32);
        in_progress.set_source(Some(Arc::new(source)));
        in_progress.copy_rows_by_filter(&predicate).unwrap();

        let result = in_progress.finish().unwrap();
        let result = result.as_primitive::<Int32Type>();
        let expected = Int32Array::from(vec![
            None,
            Some(1),
            Some(2),
            Some(4),
            None,
            Some(6),
            Some(7),
            Some(8),
            None,
            Some(11),
            Some(12),
            Some(13),
            Some(14),
            None,
        ]);
        assert_eq!(result, &expected);
    }

    #[test]
    fn test_copy_rows_by_filter_rejects_all_filter_longer_than_source() {
        let source: ArrayRef = Arc::new(Int32Array::from(vec![1, 2, 3]));
        let mut in_progress = InProgressPrimitiveArray::<Int32Type>::new(4, DataType::Int32);
        in_progress.set_source(Some(source));

        let filter = BooleanArray::from(vec![true; 4]);
        let predicate = FilterBuilder::new(&filter).build();
        assert!(matches!(predicate.selection(), FilterSelection::All { .. }));

        let err = in_progress.copy_rows_by_filter(&predicate).unwrap_err();
        assert!(matches!(
            err,
            ArrowError::InvalidArgumentError(message)
                if message == "Filter predicate of length 4 is larger than source array of length 3"
        ));
    }

    #[test]
    fn test_size_empty() {
        // A fresh in-progress array has allocated nothing yet
        let in_progress = InProgressPrimitiveArray::<Int32Type>::new(64, DataType::Int32);
        assert_eq!(in_progress.size(), 0);
    }

    #[test]
    fn test_size_counts_source() {
        let mut in_progress = InProgressPrimitiveArray::<Int32Type>::new(64, DataType::Int32);
        let source: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
        in_progress.set_source(Some(Arc::clone(&source)));
        // Nothing copied yet, so size is exactly the source's memory
        assert_eq!(in_progress.size(), source.get_array_memory_size());
    }

    #[test]
    fn test_size_counts_values_buffer_and_resets_on_finish() {
        const BATCH_SIZE: usize = 64;
        let mut in_progress =
            InProgressPrimitiveArray::<Int32Type>::new(BATCH_SIZE, DataType::Int32);
        // Non-null source: the nulls builder stays empty (allocated_size == 0),
        // so the only growth is the values buffer.
        let source: ArrayRef = Arc::new(Int32Array::from_iter_values(0..100));
        let source_size = source.get_array_memory_size();
        in_progress.set_source(Some(Arc::clone(&source)));

        in_progress.copy_rows(0, 50).unwrap();
        assert!(
            in_progress.size() >= source_size + 50 * size_of::<i32>(),
            "values buffer under-counted: {} < {} + {} * {}",
            in_progress.size(),
            source_size,
            50,
            size_of::<i32>(),
        );

        // finish() takes the buffered values/nulls but keeps the source, so the
        // reported size drops back to exactly the source.
        in_progress.finish().unwrap();
        assert_eq!(in_progress.size(), source_size);
    }

    #[test]
    fn test_size_counts_null_buffer() {
        const BATCH_SIZE: usize = 64;

        let in_progress_bytes = |source: ArrayRef| {
            let mut in_progress =
                InProgressPrimitiveArray::<Int32Type>::new(BATCH_SIZE, DataType::Int32);
            let source_len = source.len();
            in_progress.set_source(Some(source));
            in_progress.copy_rows(0, source_len / 2).unwrap();
            in_progress.size()
        };

        // All values valid: the nulls builder never allocates.
        let all_valid = in_progress_bytes(Arc::new(Int32Array::from_iter_values(0..100)));
        // Some values null: copying materializes a null buffer that must count.
        let with_nulls = in_progress_bytes(Arc::new(Int32Array::from_iter(
            (0..100).map(|i| (i % 2 == 0).then_some(i)),
        )));

        assert!(
            with_nulls > all_valid,
            "null buffer must be included in size(): with_nulls={with_nulls} all_valid={all_valid}"
        );
    }

    #[test]
    fn test_copy_rows_by_indices() {
        let source: ArrayRef = Arc::new(Int32Array::from_iter(
            (0..32i32).map(|i| if i % 3 == 0 { None } else { Some(i) }),
        ));
        let indices = UInt32Array::from(vec![
            0u32, 15, 2, 7, 3, 9, 12, 1, 20, 15, 6, 8, 11, 18, 21, 24, 30,
        ]);

        let mut in_progress = InProgressPrimitiveArray::<Int32Type>::new(32, DataType::Int32);
        // SAFETY: `indices` contains no nulls and every index is less than `source.len()`.
        unsafe { in_progress.copy_rows_by_indices(&source, &indices).unwrap() };
        let actual = in_progress.finish().unwrap();

        let expected = take(source.as_ref(), &indices, None).unwrap();
        assert_eq!(actual.as_ref(), expected.as_ref());
    }
}