This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-12212-e4d721a454e521b639f2844cf9feac4e50beaa69
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git

commit 6ca7f3093dd93728799ed6b93b334dfafce686f8
Author: RIchard Baah <[email protected]>
AuthorDate: Sat Nov 14 02:37:42 2026 +0000

    perf(coalesce): hoist indexed ByteView buffer checks (#12212)
    
    # Which issue does this PR close?
    
    Closes #12210.
    
    # Rationale for this change
    
    The sparse ByteView indexed-copy path added in #11174 checks the
    destination buffer boundary for every selected non-inline value, even
    though it already computes the total selected byte length before
    copying.
    
    # What changes are included in this PR?
    
    Before this change, one loop handled both cases. For every selected
    non-inline value it computed the destination end, checked whether the
    value crossed the buffer limit, potentially finalized the buffer and
    allocated another one, and then copied the value.
    
    The caller already knows the total selected byte length. This change
    uses that total once before the loop:
    
    - If all selected bytes fit, the common path copies them into one buffer
    without checking the split boundary for every value.
    - If they do not fit, it calls a cold helper containing the existing
    split-buffer loop.
    
    The diff looks larger because it adds the specialized common loop and
    moves the old general loop into the helper; the split-buffer behavior is
    unchanged. In generated code, the common loop goes from two destination
    checks to one: the split-buffer threshold branch is removed, while
    `Vec::extend_from_slice`'s capacity guard remains.
    
    <details>
    <summary>Assembly comparison and reproduction</summary>
    
    Verified at base `b8d7b68bfc` and head `e619f21624` with `rustc 1.99.1`
    on `aarch64-apple-darwin`.
    
    Base, before the copy:
    
    ```asm
    add  x8, x27, x10
    lsr  x8, x8, #31
    cbz  x8, ...       // continue when dst_len + value_len fits
    ```
    
    Both revisions retain the `Vec` capacity guard around `memcpy`:
    
    ```asm
    sub  x8, x8, x21
    cmp  x27, x8
    b.hi ...           // grow Vec when remaining capacity is too small
    ```
    
    At the PR head, the first sequence is absent from the common loop. To
    check either revision:
    
    ```bash
    RUSTFLAGS='-C target-cpu=native' cargo rustc \
      -p arrow --bench coalesce_kernels --release \
      --features test_utils -- --emit=asm
    
    BIN=$(rg --files target/release/deps | \
      rg '/coalesce_kernels-[^.]+$' | head -1)
    objdump -d "$BIN" | rustfilt | less
    ```
    
    Search the disassembly for `append_indexed_views_and_copy_strings`. Run
    the commands at `b8d7b68bfc` and `e619f21624` to compare the two loops.
    Install `rustfilt` with `cargo install rustfilt` if needed.
    
    </details>
    
    The existing overflow checks and maximum buffer size are preserved.
    
    # Are these changes tested?
    
    `test_copy_rows_by_indices_compacts_into_single_buffer` sets
    `max_buffer_size` equal to the selected byte length, covering the
    exact-fit fast path and validating the output layout. The existing
    split-buffer test covers `selected_bytes > max_buffer_size`, so both
    sides of the new dispatch are exercised.
    
    The final reruns compare the PR head `e619f21624` with its parent
    `b8d7b68bfc`.
    
    | Benchmark | Result | Runs |
    | --- | --- | --- |
    | `coalesce_kernels` (ARM64) | 1% selections are 7-13% faster; 0.1%
    selections are 2-5% faster |
    
[results](https://github.com/apache/arrow-rs/pull/12212#issuecomment-6836529176)
    |
    | `coalesce_kernels` (AMD64) | Seven cases are 2-18% faster; BinaryView
    with no nulls at 1% is 3-4% slower in two runs | [full
    run](https://github.com/apache/arrow-rs/pull/12212#issuecomment-6836729576),
    
[rerun](https://github.com/apache/arrow-rs/pull/12212#issuecomment-6836811569)
    |
    | Focused Utf8View rerun (ARM64) | All four cases are 3-10% faster |
    
[results](https://github.com/apache/arrow-rs/pull/12212#issuecomment-6841374361)
    |
    | Focused Utf8View rerun (AMD64) | All four cases are 7-15% faster |
    
[results](https://github.com/apache/arrow-rs/pull/12212#issuecomment-6841326819)
    |
    
    # Are there any significant user-facing changes?
    
    No.
---
 arrow-select/src/coalesce/byte_view.rs | 108 +++++++++++++++++++++++++++++++++
 1 file changed, 108 insertions(+)

diff --git a/arrow-select/src/coalesce/byte_view.rs 
b/arrow-select/src/coalesce/byte_view.rs
index 3616167cd9..2e7ebf61c0 100644
--- a/arrow-select/src/coalesce/byte_view.rs
+++ b/arrow-select/src/coalesce/byte_view.rs
@@ -393,6 +393,8 @@ impl<B: ByteViewType> InProgressByteViewArray<B> {
     ///
     /// Every value in `indices` must be less than `src_views.len()`, and every
     /// selected non-inline view must reference a valid range in `src_buffers`.
+    /// `selected_bytes` must equal the total length of the selected non-inline
+    /// values, and every selected value must fit within `i32::MAX` bytes.
     #[inline(never)]
     unsafe fn append_indexed_views_and_copy_strings(
         &mut self,
@@ -418,6 +420,8 @@ impl<B: ByteViewType> InProgressByteViewArray<B> {
     ///
     /// Every value in `indices` must be less than `src_views.len()`, and every
     /// selected non-inline view must reference a valid range in `src_buffers`.
+    /// `selected_bytes` must equal the total length of the selected non-inline
+    /// values, and every selected value must fit within `max_buffer_size`.
     unsafe fn append_indexed_views_and_copy_strings_with_max_buffer_size(
         &mut self,
         src_views: &[u128],
@@ -462,6 +466,77 @@ impl<B: ByteViewType> InProgressByteViewArray<B> {
                 .next_buffer(selected_bytes.min(max_buffer_size)),
         };
 
+        if selected_bytes > max_buffer_size {
+            // SAFETY: the caller guarantees the index, view, byte-count, and
+            // per-value size invariants required by the delegated operation.
+            unsafe {
+                self.append_indexed_views_and_copy_strings_split(
+                    src_views,
+                    indices,
+                    src_buffers,
+                    selected_bytes,
+                    max_buffer_size,
+                    dst_buffer,
+                )
+            };
+            return;
+        }
+
+        let current_len = self.views.len();
+        self.views.reserve(indices.len());
+        let output = 
self.views.spare_capacity_mut().as_mut_ptr().cast::<u128>();
+
+        let buffer_index = self.completed.len().try_into().expect("too many 
buffers");
+        for (i, &idx) in indices.iter().enumerate() {
+            // SAFETY: caller validated idx < src_views.len().
+            let raw = unsafe { *src_views.get_unchecked(idx as usize) };
+            let mut view = ByteView::from(raw);
+            if view.length > MAX_INLINE_VIEW_LEN {
+                let source_buffer_index = view.buffer_index as usize;
+                let source_buffer_offset = view.offset as usize;
+                let length = view.length as usize;
+
+                // SAFETY: source views carry valid buffer_index/offset/length.
+                let src = unsafe {
+                    src_buffers
+                        .get_unchecked(source_buffer_index)
+                        
.get_unchecked(source_buffer_offset..source_buffer_offset + length)
+                };
+                view.offset = dst_buffer
+                    .len()
+                    .try_into()
+                    .expect("byte view offset exceeds u32::MAX");
+                view.buffer_index = buffer_index;
+                debug_assert!(dst_buffer.capacity() - dst_buffer.len() >= 
length);
+                dst_buffer.extend_from_slice(src);
+            }
+            // SAFETY: `reserve` above allocated room for every selected view.
+            unsafe { output.add(i).write(view.as_u128()) };
+        }
+        // SAFETY: the loop above initialized exactly `indices.len()` views.
+        unsafe { self.views.set_len(current_len + indices.len()) };
+        self.current = Some(dst_buffer);
+    }
+
+    /// Copies indexed views into bounded output buffers.
+    ///
+    /// # Safety
+    ///
+    /// Every value in `indices` must be less than `src_views.len()`, every
+    /// selected non-inline view must reference a valid range in `src_buffers`,
+    /// every selected value must fit within `max_buffer_size`, and
+    /// `selected_bytes` must equal their total length.
+    #[cold]
+    #[inline(never)]
+    unsafe fn append_indexed_views_and_copy_strings_split(
+        &mut self,
+        src_views: &[u128],
+        indices: &[u32],
+        src_buffers: &[Buffer],
+        selected_bytes: usize,
+        max_buffer_size: usize,
+        mut dst_buffer: Vec<u8>,
+    ) {
         let current_len = self.views.len();
         self.views.reserve(indices.len());
         let output = 
self.views.spare_capacity_mut().as_mut_ptr().cast::<u128>();
@@ -1194,6 +1269,39 @@ mod tests {
         }
     }
 
+    #[test]
+    fn test_copy_rows_by_indices_compacts_into_single_buffer() {
+        let (array, _) = non_inline_array(8);
+        let source: ArrayRef = Arc::new(array);
+        let indices = [0u32, 3, 7];
+        let typed = source.as_binary_view();
+        // SAFETY: every index is less than `typed.views().len()`.
+        let selected_bytes =
+            unsafe { selected_non_inline_bytes(typed.views(), &indices, 
usize::MAX) }.unwrap();
+
+        let mut in_progress = 
InProgressByteViewArray::<BinaryViewType>::new(16);
+        in_progress.nulls.append_n_non_nulls(indices.len());
+        // SAFETY: every index selects a valid view from `typed`, whose views 
and
+        // buffers come from the same validated ByteView array.
+        unsafe {
+            
in_progress.append_indexed_views_and_copy_strings_with_max_buffer_size(
+                typed.views(),
+                &indices,
+                typed.data_buffers(),
+                selected_bytes,
+                selected_bytes,
+            );
+        }
+        let actual = in_progress.finish().unwrap();
+
+        let expected = take(source.as_ref(), 
&UInt32Array::from(indices.to_vec()), None).unwrap();
+        assert_eq!(actual.as_ref(), expected.as_ref());
+        let actual = actual.as_binary_view();
+        assert_eq!(actual.data_buffers().len(), 1);
+        assert_eq!(actual.data_buffers()[0].len(), selected_bytes);
+        actual.to_data().validate_full().unwrap();
+    }
+
     #[test]
     fn test_copy_rows_by_indices_splits_compacted_buffers() {
         let (array, _) = non_inline_array(8);

Reply via email to