Skip to main content

arrow_data/transform/
run.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: See the NOTICE file distributed with this work for additional information regarding copyright ownership
3// SPDX-FileContributor: Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements
4
5use super::{_MutableArrayData, ArrayData, Extend};
6use arrow_buffer::{ArrowNativeType, ToByteSlice};
7use arrow_schema::{ArrowError, DataType};
8use num_traits::CheckedAdd;
9
10/// Generic helper to get the last run end value from a run ends array
11fn get_last_run_end<T: ArrowNativeType>(run_ends_data: &super::MutableArrayData) -> T {
12    if run_ends_data.data.len == 0 {
13        T::default()
14    } else {
15        let typed_slice: &[T] = run_ends_data.data.buffer1.typed_data();
16        if typed_slice.len() >= run_ends_data.data.len {
17            typed_slice[run_ends_data.data.len - 1]
18        } else {
19            T::default()
20        }
21    }
22}
23
24/// Extends the `MutableArrayData` with null values.
25///
26/// For RunEndEncoded, this adds nulls by extending the run_ends array
27/// and values array appropriately.
28pub fn extend_nulls(mutable: &mut _MutableArrayData, len: usize) -> Result<(), ArrowError> {
29    if len == 0 {
30        return Ok(());
31    }
32
33    // For REE, we always need to add a value entry when adding a new run
34    // The values array should have one entry per run, not per logical element
35    mutable.child_data[1].try_extend_nulls(1)?;
36
37    // Determine the run end type from the data type
38    let run_end_type = if let DataType::RunEndEncoded(run_ends_field, _) = &mutable.data_type {
39        run_ends_field.data_type()
40    } else {
41        panic!("extend_nulls called on non-RunEndEncoded array");
42    };
43
44    // Use a macro to handle all run end types generically
45    macro_rules! extend_nulls_impl {
46        ($run_end_type:ty) => {{
47            let last_run_end = get_last_run_end::<$run_end_type>(&mutable.child_data[0]);
48            let len = <$run_end_type as ArrowNativeType>::from_usize(len);
49            let new_value = len
50                .and_then(|len| last_run_end.checked_add(len))
51                .ok_or_else(|| {
52                    ArrowError::InvalidArgumentError(
53                        "run end overflow when extending RunEndEncoded array: \
54                         use a larger run-end type (e.g. Int64 instead of Int32)"
55                            .to_string(),
56                    )
57                })?;
58            mutable.child_data[0]
59                .data
60                .buffer1
61                .try_extend_from_slice(new_value.to_byte_slice())
62                .map_err(|e| ArrowError::MemoryError(e.to_string()))?;
63        }};
64    }
65
66    // Apply the appropriate implementation based on run end type
67    match run_end_type {
68        DataType::Int16 => extend_nulls_impl!(i16),
69        DataType::Int32 => extend_nulls_impl!(i32),
70        DataType::Int64 => extend_nulls_impl!(i64),
71        _ => panic!("Invalid run end type for RunEndEncoded array: {run_end_type}"),
72    }
73
74    mutable.child_data[0].data.len += 1;
75    Ok(())
76}
77
78/// The run-ends bytes and optional values index range returned by [`build_extend_arrays`].
79type ExtendArrays = (Vec<u8>, Option<(usize, usize)>);
80
81/// Build run ends bytes and values range directly for batch processing
82fn build_extend_arrays<T: ArrowNativeType + std::ops::Add<Output = T> + CheckedAdd>(
83    typed_slice: &[T],
84    length: usize,
85    start: usize,
86    len: usize,
87    dest_last_run_end: T,
88) -> Result<ExtendArrays, ArrowError> {
89    let mut run_ends_bytes = Vec::new();
90    let mut values_range: Option<(usize, usize)> = None;
91    let end = start + len;
92    let mut prev_end = 0;
93    let mut current_run_end = dest_last_run_end;
94
95    for i in 0..length {
96        if i < typed_slice.len() {
97            let run_end = typed_slice[i].to_usize().unwrap();
98
99            if prev_end <= start && run_end > start {
100                let start_offset = start - prev_end;
101                let end_offset = if run_end >= end {
102                    end - prev_end
103                } else {
104                    run_end - prev_end
105                };
106                current_run_end = current_run_end
107                    .checked_add(&T::usize_as(end_offset - start_offset))
108                    .ok_or_else(|| {
109                        ArrowError::InvalidArgumentError(
110                            "run end overflow when extending RunEndEncoded array: \
111                         use a larger run-end type (e.g. Int64 instead of Int32)"
112                                .to_string(),
113                        )
114                    })?;
115                run_ends_bytes.extend_from_slice(current_run_end.to_byte_slice());
116
117                // Start the range
118                values_range = Some((i, i + 1));
119            } else if prev_end >= start && run_end <= end {
120                current_run_end = current_run_end
121                    .checked_add(&T::usize_as(run_end - prev_end))
122                    .ok_or_else(|| {
123                        ArrowError::InvalidArgumentError(
124                            "run end overflow when extending RunEndEncoded array: \
125                         use a larger run-end type (e.g. Int64 instead of Int32)"
126                                .to_string(),
127                        )
128                    })?;
129                run_ends_bytes.extend_from_slice(current_run_end.to_byte_slice());
130
131                // Extend the range
132                values_range = Some((values_range.expect("Unreachable: values_range cannot be None when prev_end >= start && run_end <= end. \
133                           If prev_end >= start and run_end > prev_end (required for valid runs), then run_end > start, \
134                           which means the first condition (prev_end <= start && run_end > start) would have been true \
135                           and already set values_range to Some.").0, i + 1));
136            } else if prev_end < end && run_end >= end {
137                current_run_end = current_run_end
138                    .checked_add(&T::usize_as(end - prev_end))
139                    .ok_or_else(|| {
140                        ArrowError::InvalidArgumentError(
141                            "run end overflow when extending RunEndEncoded array: \
142                         use a larger run-end type (e.g. Int64 instead of Int32)"
143                                .to_string(),
144                        )
145                    })?;
146                run_ends_bytes.extend_from_slice(current_run_end.to_byte_slice());
147
148                // Extend the range and break
149                values_range = Some((values_range.expect("Unreachable: values_range cannot be None when prev_end < end && run_end >= end. \
150                           Due to sequential processing and monotonic prev_end advancement, if we reach a run \
151                           that spans beyond the slice end (run_end >= end), at least one previous condition \
152                           must have matched first to set values_range. Either the first condition matched when \
153                           the slice started (prev_end <= start && run_end > start), or the second condition \
154                           matched for runs within the slice (prev_end >= start && run_end <= end).").0, i + 1));
155                break;
156            }
157
158            prev_end = run_end;
159            if prev_end >= end {
160                break;
161            }
162        } else {
163            break;
164        }
165    }
166    Ok((run_ends_bytes, values_range))
167}
168
169/// Process extends using batch operations
170fn process_extends_batch<T: ArrowNativeType>(
171    mutable: &mut _MutableArrayData,
172    source_array_idx: usize,
173    run_ends_bytes: Vec<u8>,
174    values_range: Option<(usize, usize)>,
175) -> Result<(), ArrowError> {
176    if run_ends_bytes.is_empty() {
177        return Ok(());
178    }
179
180    // Batch extend the run_ends array with all bytes at once
181    mutable.child_data[0]
182        .data
183        .buffer1
184        .extend_from_slice(&run_ends_bytes);
185    mutable.child_data[0].data.len += run_ends_bytes.len() / std::mem::size_of::<T>();
186
187    // Batch extend the values array using the range
188    let (start_idx, end_idx) =
189        values_range.expect("values_range should be Some if run_ends_bytes is not empty");
190    mutable.child_data[1].try_extend(source_array_idx, start_idx, end_idx)
191}
192
193/// Returns a function that extends the run encoded array.
194///
195/// It finds the physical indices in the source array that correspond to the logical range to copy, and adjusts the runs to the logical indices of the array to extend. The values are copied from the source array to the destination array verbatim.
196pub fn build_extend(array: &ArrayData) -> Extend<'_> {
197    Box::new(
198        move |mutable: &mut _MutableArrayData, array_idx: usize, start: usize, len: usize| {
199            if len == 0 {
200                return Ok(());
201            }
202
203            // We need to analyze the source array's run structure
204            let source_run_ends = &array.child_data()[0];
205            let source_buffer_offset = source_run_ends.offset();
206            let source_buffer_len = source_run_ends.len();
207            let source_buffer = &source_run_ends.buffers()[0];
208
209            // Get the run end type from the mutable array
210            let dest_run_end_type =
211                if let DataType::RunEndEncoded(run_ends_field, _) = &mutable.data_type {
212                    run_ends_field.data_type()
213                } else {
214                    panic!("extend called on non-RunEndEncoded mutable array");
215                };
216
217            // Build run ends and values indices directly for batch processing
218            macro_rules! build_and_process_impl {
219                ($run_end_type:ty) => {{
220                    let source_buffer = &source_buffer.typed_data()
221                        [source_buffer_offset..source_buffer_offset + source_buffer_len];
222                    let dest_last_run_end =
223                        get_last_run_end::<$run_end_type>(&mutable.child_data[0]);
224                    let (run_ends_bytes, values_range) = build_extend_arrays::<$run_end_type>(
225                        source_buffer,
226                        source_run_ends.len(),
227                        start + array.offset(),
228                        len,
229                        dest_last_run_end,
230                    )?;
231                    process_extends_batch::<$run_end_type>(
232                        mutable,
233                        array_idx,
234                        run_ends_bytes,
235                        values_range,
236                    )?;
237                }};
238            }
239
240            match dest_run_end_type {
241                DataType::Int16 => build_and_process_impl!(i16),
242                DataType::Int32 => build_and_process_impl!(i32),
243                DataType::Int64 => build_and_process_impl!(i64),
244                _ => panic!("Invalid run end type for RunEndEncoded array: {dest_run_end_type}"),
245            }
246            Ok(())
247        },
248    )
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254    use crate::transform::MutableArrayData;
255    use crate::{ArrayData, ArrayDataBuilder};
256    use arrow_buffer::Buffer;
257    use arrow_schema::{DataType, Field};
258    use rstest::rstest;
259    use std::sync::Arc;
260
261    fn create_run_array_data<T: ArrowNativeType>(
262        run_ends: Vec<T>,
263        values: ArrayData,
264        run_end_type: DataType,
265    ) -> ArrayData {
266        let run_ends_field = Arc::new(Field::new(
267            Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
268            run_end_type.clone(),
269            false,
270        ));
271        let values_field = Arc::new(Field::new(
272            Field::REE_VALUES_FIELD_DEFAULT_NAME,
273            values.data_type().clone(),
274            true,
275        ));
276        let data_type = DataType::RunEndEncoded(run_ends_field, values_field);
277
278        let last_run_end = if run_ends.is_empty() {
279            0
280        } else {
281            run_ends[run_ends.len() - 1].as_usize()
282        };
283
284        let run_ends_buffer = Buffer::from_vec(run_ends);
285        let run_ends_data = ArrayDataBuilder::new(run_end_type)
286            .len(run_ends_buffer.len() / std::mem::size_of::<T>())
287            .add_buffer(run_ends_buffer)
288            .build()
289            .unwrap();
290
291        ArrayDataBuilder::new(data_type)
292            .len(last_run_end)
293            .add_child_data(run_ends_data)
294            .add_child_data(values)
295            .build()
296            .unwrap()
297    }
298
299    fn create_int32_array_data(values: Vec<i32>) -> ArrayData {
300        let buffer = Buffer::from_vec(values);
301        ArrayDataBuilder::new(DataType::Int32)
302            .len(buffer.len() / std::mem::size_of::<i32>())
303            .add_buffer(buffer)
304            .build()
305            .unwrap()
306    }
307
308    fn create_string_dict_array_data(values: Vec<&str>, dict_values: Vec<&str>) -> ArrayData {
309        // Create dictionary values (strings)
310        let dict_offsets: Vec<i32> = dict_values
311            .iter()
312            .scan(0i32, |acc, s| {
313                let offset = *acc;
314                *acc += s.len() as i32;
315                Some(offset)
316            })
317            .chain(std::iter::once(
318                dict_values.iter().map(|s| s.len()).sum::<usize>() as i32,
319            ))
320            .collect();
321
322        let dict_data: Vec<u8> = dict_values.iter().flat_map(|s| s.bytes()).collect();
323
324        let dict_array = ArrayDataBuilder::new(DataType::Utf8)
325            .len(dict_values.len())
326            .add_buffer(Buffer::from_vec(dict_offsets))
327            .add_buffer(Buffer::from_vec(dict_data))
328            .build()
329            .unwrap();
330
331        // Create keys array
332        let keys: Vec<i32> = values
333            .iter()
334            .map(|v| dict_values.iter().position(|d| d == v).unwrap() as i32)
335            .collect();
336
337        // Create dictionary array
338        let dict_type = DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8));
339
340        ArrayDataBuilder::new(dict_type)
341            .len(values.len())
342            .add_buffer(Buffer::from_vec(keys))
343            .add_child_data(dict_array)
344            .build()
345            .unwrap()
346    }
347
348    #[test]
349    fn test_extend_nulls_int32() {
350        // Create values array with one value
351        let values = create_int32_array_data(vec![42]);
352
353        // Create REE array with Int32 run ends
354        let ree_array = create_run_array_data::<i32>(vec![5_i32], values, DataType::Int32);
355
356        let mut mutable = MutableArrayData::new(vec![&ree_array], true, 10);
357
358        mutable.try_extend_nulls(3).unwrap();
359        mutable.try_extend(0, 0, 5).unwrap();
360        mutable.try_extend_nulls(3).unwrap();
361
362        // Verify the run ends were extended correctly
363        let result = mutable.freeze();
364        let run_ends_buffer = &result.child_data()[0].buffers()[0];
365        let run_ends_slice = run_ends_buffer.as_slice();
366
367        // Should have three run ends now
368        assert_eq!(result.child_data()[0].len(), 3);
369        let first_run_end = i32::from_ne_bytes(run_ends_slice[0..4].try_into().unwrap());
370        let second_run_end = i32::from_ne_bytes(run_ends_slice[4..8].try_into().unwrap());
371        let third_run_end = i32::from_ne_bytes(run_ends_slice[8..12].try_into().unwrap());
372        assert_eq!(first_run_end, 3);
373        assert_eq!(second_run_end, 8);
374        assert_eq!(third_run_end, 11);
375
376        // Verify the values array was extended correctly
377        assert_eq!(result.child_data()[1].len(), 3); // Should match run ends length
378        let values_buffer = &result.child_data()[1].buffers()[0];
379        let values_slice = values_buffer.as_slice();
380
381        // Check the values in the buffer
382        let second_value = i32::from_ne_bytes(values_slice[4..8].try_into().unwrap());
383
384        // Second value should be the original value from the source array
385        assert_eq!(second_value, 42);
386
387        // Verify the validity buffer shows the correct null pattern
388        let values_array = &result.child_data()[1];
389        // First value should be null
390        assert!(values_array.is_null(0));
391        // Second value should be valid
392        assert!(values_array.is_valid(1));
393        // Third value should be null
394        assert!(values_array.is_null(2));
395    }
396
397    #[rstest]
398    #[case::int16(DataType::Int16, [5_i16], [5_i16, 8])]
399    #[case::int64(DataType::Int64, [5_i64], [5_i64, 8])]
400    fn test_extend_nulls_after_values<T: ArrowNativeType>(
401        #[case] run_end_type: DataType,
402        #[case] run_ends: [T; 1],
403        #[case] expected: [T; 2],
404    ) {
405        let values = create_int32_array_data(vec![42]);
406        let ree_array = create_run_array_data::<T>(run_ends.to_vec(), values, run_end_type);
407        let mut mutable = MutableArrayData::new(vec![&ree_array], true, 10);
408
409        mutable.try_extend(0, 0, 5).unwrap();
410        mutable.try_extend_nulls(3).unwrap();
411
412        let result = mutable.freeze();
413        let run_ends = &result.child_data()[0];
414        assert_eq!(run_ends.len(), 2);
415        assert_eq!(run_ends.buffers()[0].typed_data::<T>(), &expected);
416    }
417
418    #[test]
419    fn test_extend_int32() {
420        // Create a simple REE array with Int32 run ends
421        let values = create_int32_array_data(vec![10, 20]);
422
423        // Array: [10, 10, 20, 20, 20] (run_ends = [2, 5])
424        let ree_array = create_run_array_data::<i32>(vec![2_i32, 5], values, DataType::Int32);
425
426        let mut mutable = MutableArrayData::new(vec![&ree_array], false, 10);
427
428        // Extend the entire array
429        mutable.try_extend(0, 0, 5).unwrap();
430
431        let result = mutable.freeze();
432
433        // Should have extended correctly
434        assert_eq!(result.len(), 5); // All 5 elements
435
436        // Basic validation that we have the right structure
437        assert!(!result.child_data()[0].is_empty()); // Should have at least one run
438        assert_eq!(result.child_data()[0].len(), result.child_data()[1].len()); // run_ends and values should have same length
439    }
440
441    #[test]
442    fn test_extend_empty() {
443        let values = create_int32_array_data(vec![]);
444        let ree_array = create_run_array_data::<i32>(vec![], values, DataType::Int32);
445
446        let mut mutable = MutableArrayData::new(vec![&ree_array], false, 10);
447        mutable.try_extend(0, 0, 0).unwrap();
448
449        let result = mutable.freeze();
450        assert_eq!(result.len(), 0);
451        assert_eq!(result.child_data()[0].len(), 0);
452    }
453
454    #[rstest]
455    #[case::int16([3_i16, 5, 8], 0_i16, [1_i16, 3, 4])]
456    #[case::int64([3_i64, 5, 8], 0_i64, [1_i64, 3, 4])]
457    fn test_build_extend_arrays<T>(
458        #[case] run_ends: [T; 3],
459        #[case] dest_last_run_end: T,
460        #[case] expected: [T; 3],
461    ) where
462        T: ArrowNativeType + CheckedAdd,
463    {
464        let buffer = Buffer::from_vec(run_ends.to_vec());
465        let (run_ends_bytes, values_range) =
466            build_extend_arrays::<T>(buffer.typed_data(), 3, 2, 4, dest_last_run_end).unwrap();
467
468        // Logical array: [A, A, A, B, B, C, C, C]
469        // Requesting indices 2-6 should give us:
470        // - Part of first run (index 2) -> length 1
471        // - All of second run -> length 2
472        // - Part of third run -> length 1
473        // Total length = 4, so run ends should be [1, 3, 4]
474        assert_eq!(run_ends_bytes.len(), 3 * std::mem::size_of::<T>());
475        assert_eq!(values_range, Some((0, 3)));
476        assert_eq!(run_ends_bytes, expected.as_slice().to_byte_slice());
477    }
478
479    #[test]
480    fn test_extend_string_dict() {
481        // Create a dictionary array with string values: ["hello", "world"]
482        let dict_values = vec!["hello", "world"];
483        let values = create_string_dict_array_data(vec!["hello", "world"], dict_values);
484
485        // Create REE array: [hello, hello, world, world, world] (run_ends = [2, 5])
486        let ree_array = create_run_array_data::<i32>(vec![2_i32, 5], values, DataType::Int32);
487
488        let mut mutable = MutableArrayData::new(vec![&ree_array], false, 10);
489
490        // Extend the entire array
491        mutable.try_extend(0, 0, 5).unwrap();
492
493        let result = mutable.freeze();
494
495        // Should have extended correctly
496        assert_eq!(result.len(), 5); // All 5 elements
497
498        // Basic validation that we have the right structure
499        assert!(!result.child_data()[0].is_empty()); // Should have at least one run
500        assert_eq!(result.child_data()[0].len(), result.child_data()[1].len()); // run_ends and values should have same length
501
502        // Should have 2 runs since we have 2 different values
503        assert_eq!(result.child_data()[0].len(), 2);
504        assert_eq!(result.child_data()[1].len(), 2);
505    }
506
507    #[rstest]
508    #[case::int16(5_i16, i16::MAX, DataType::Int16)]
509    #[case::int32(10_i32, i32::MAX, DataType::Int32)]
510    fn test_extend_nulls_run_end_overflow<T: ArrowNativeType>(
511        #[case] initial_run_end: T,
512        #[case] null_count: T,
513        #[case] run_end_type: DataType,
514    ) {
515        let values = create_int32_array_data(vec![42]);
516        let ree_array = create_run_array_data::<T>(vec![initial_run_end], values, run_end_type);
517        let mut mutable = MutableArrayData::new(vec![&ree_array], true, 10);
518
519        // Extend the original data first to initialize state
520        mutable
521            .try_extend(0, 0, initial_run_end.as_usize())
522            .unwrap();
523
524        // The null count fits in T, but adding it to the existing run end overflows.
525        let err = mutable.try_extend_nulls(null_count.as_usize()).unwrap_err();
526        assert!(
527            err.to_string().contains("run end overflow"),
528            "unexpected error: {err}"
529        );
530    }
531
532    #[rstest]
533    #[case::int16(20_i16, i16::MAX - 5, DataType::Int16)]
534    #[case::int32(100_i32, i32::MAX - 50, DataType::Int32)]
535    fn test_build_extend_overflow<T: ArrowNativeType>(
536        #[case] src_value: T,
537        #[case] dest_value: T,
538        #[case] run_end_type: DataType,
539    ) {
540        // Create a source array with small run that will cause overflow when added
541        let values = create_int32_array_data(vec![10]);
542        let source_array =
543            create_run_array_data::<T>(vec![src_value], values, run_end_type.clone());
544
545        // Create a destination array with run end close to max
546        let dest_values = create_int32_array_data(vec![42]);
547        let dest_array = create_run_array_data::<T>(vec![dest_value], dest_values, run_end_type);
548
549        let mut mutable = MutableArrayData::new(vec![&source_array, &dest_array], false, 10);
550
551        // First extend the destination array to set up state
552        mutable.try_extend(1, 0, dest_value.as_usize()).unwrap();
553
554        // This should return an error: dest_value + src_value exceeds the run-end type's maximum.
555        let err = mutable.try_extend(0, 0, src_value.as_usize()).unwrap_err();
556        assert!(
557            err.to_string().contains("run end overflow"),
558            "unexpected error: {err}"
559        );
560    }
561
562    #[test]
563    fn test_extend_nulls_length_overflow() {
564        let values = create_int32_array_data(vec![10]);
565        let array = create_run_array_data::<i16>(vec![100_i16], values, DataType::Int16);
566
567        let mut mutable = MutableArrayData::new(vec![&array], true, 10);
568        let err = mutable.try_extend_nulls(i16::MAX as usize + 1).unwrap_err();
569        assert_eq!(
570            err.to_string(),
571            "Invalid argument error: run end overflow when extending RunEndEncoded array: use a larger run-end type (e.g. Int64 instead of Int32)"
572        );
573    }
574
575    #[test]
576    fn test_extend_accounts_for_offset() {
577        let dt = DataType::RunEndEncoded(
578            Arc::new(Field::new(
579                Field::REE_RUN_ENDS_FIELD_DEFAULT_NAME,
580                DataType::Int32,
581                false,
582            )),
583            Arc::new(Field::new(
584                Field::REE_VALUES_FIELD_DEFAULT_NAME,
585                DataType::Float32,
586                true,
587            )),
588        );
589
590        let runs = ArrayData::builder(DataType::Int32)
591            .len(2)
592            .offset(2)
593            .add_buffer(vec![-10_i32, -20, 1_i32, 4, 0, 100].into())
594            .build()
595            .unwrap();
596        let values = ArrayData::builder(DataType::Float32)
597            .len(2)
598            .add_buffer(vec![1.5, 2.5].into())
599            .build()
600            .unwrap();
601
602        let source_data = ArrayDataBuilder::new(dt)
603            .len(3)
604            .child_data(vec![runs, values])
605            .build()
606            .unwrap();
607
608        let mut mutable = MutableArrayData::new(vec![&source_data], true, 10);
609        mutable.try_extend(0, 0, 1).unwrap();
610        let data = mutable.freeze();
611        assert_eq!(data, source_data.slice(0, 1));
612    }
613}