You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "manishkr (via GitHub)" <gi...@apache.org> on 2026/01/18 06:45:09 UTC

[PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

manishkr opened a new pull request, #9213:
URL: https://github.com/apache/arrow-rs/pull/9213

   # Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax.
   -->
   
   - Closes #9018 .
   
   # Rationale for this change
   
   <!--
   Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
   Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.
   -->
   The existing implementation had issue for row or cast ops for RunArray. The equality implementation also did not support logical index-based comparisons.
   # What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   1. Fixed RunArray row and cast handling
   2. Added logical index based equality check for RunArray.
   # Are these changes tested?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   4. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   Yes
   # Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   
   If there are any breaking changes to public APIs, please call them out.
   -->
   No.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "manishkr (via GitHub)" <gi...@apache.org>.
manishkr commented on code in PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#discussion_r2725344151


##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,148 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: &'a [T],
+    values: &'a ArrayData,
+    abs_start: usize,
+}
 
-    if lhs.len() != rhs.len() {
-        return false;
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() >= 2,
+            "RunEndEncoded arrays are guaranteed to have at least 2 children [run_ends, values]"

Review Comment:
   Changed. Thanks.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#discussion_r2724224031


##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,148 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: &'a [T],
+    values: &'a ArrayData,
+    abs_start: usize,
+}
 
-    if lhs.len() != rhs.len() {
-        return false;
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() >= 2,
+            "RunEndEncoded arrays are guaranteed to have at least 2 children [run_ends, values]"

Review Comment:
   ```suggestion
               data.child_data().len() == 2,
               "RunEndEncoded arrays are guaranteed to have 2 children [run_ends, values]"
   ```



##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,148 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: &'a [T],
+    values: &'a ArrayData,
+    abs_start: usize,
+}
 
-    if lhs.len() != rhs.len() {
-        return false;
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() >= 2,
+            "RunEndEncoded arrays are guaranteed to have at least 2 children [run_ends, values]"
+        );
+        let run_ends_data = &data.child_data()[0];
+        let run_ends = &run_ends_data.buffers()[0].typed_data::<T>()

Review Comment:
   I do wonder if we're better off doing something like this:
   
   ```rust
           let raw_run_ends_buffer = &run_ends_data.buffers()[0];
           // SAFETY: we're reconstructing RunEndBuffer from a known valid RunArray
           let run_ends = unsafe {
               RunEndBuffer::<T>::new_unchecked(
                   raw_run_ends_buffer.clone().into(),
                   run_ends_data.offset(),
                   run_ends_data.len(),
               )
           };
   ```
   
   This way we can reuse the code to search for physical indices from `RunEndBuffer`, at the cost of a clone of `Buffer` (which is just an `Arc` and usize + ptr) 🤔  



##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,148 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: &'a [T],
+    values: &'a ArrayData,
+    abs_start: usize,
+}
 
-    if lhs.len() != rhs.len() {
-        return false;
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() >= 2,
+            "RunEndEncoded arrays are guaranteed to have at least 2 children [run_ends, values]"
+        );
+        let run_ends_data = &data.child_data()[0];
+        let run_ends = &run_ends_data.buffers()[0].typed_data::<T>()
+            [run_ends_data.offset()..run_ends_data.offset() + run_ends_data.len()];
+        let values = &data.child_data()[1];
+        Self {
+            run_ends,
+            values,
+            abs_start: data.offset() + start,
+        }
     }
 
-    let lhs_child_data = lhs.child_data();
-    let lhs_run_ends_array = &lhs_child_data[0];
-    let lhs_values_array = &lhs_child_data[1];
+    fn run_end(&self, index: usize) -> usize {
+        self.run_ends[index].as_usize()
+    }
 
-    let rhs_child_data = rhs.child_data();
-    let rhs_run_ends_array = &rhs_child_data[0];
-    let rhs_values_array = &rhs_child_data[1];
+    fn get_physical_index(&self, logical_index: usize) -> usize {
+        let logical_index = logical_index + self.abs_start;
+        if logical_index == 0 {
+            return 0;
+        }
+        match self
+            .run_ends
+            .binary_search_by(|val| val.as_usize().cmp(&logical_index))
+        {
+            Ok(idx) => idx + 1,
+            Err(idx) => idx,
+        }
+    }
 
-    if lhs_run_ends_array.len() != rhs_run_ends_array.len() {
-        return false;
+    fn get_start_end_physical_indices(&self, len: usize) -> (usize, usize) {
+        let start = self.get_physical_index(0);
+        let end = self.get_physical_index(len - 1);
+        (start, end)
     }
+}
 
-    if lhs_values_array.len() != rhs_values_array.len() {
-        return false;
+fn run_equal_inner<T: ArrowNativeType + ToPrimitive>(
+    lhs: &ArrayData,
+    rhs: &ArrayData,
+    lhs_start: usize,
+    rhs_start: usize,
+    len: usize,
+) -> bool {
+    if len == 0 {
+        return true;
+    }
+
+    let l_array = RunArrayData::<T>::new(lhs, lhs_start);
+    let r_array = RunArrayData::<T>::new(rhs, rhs_start);
+
+    let (l_start_phys, r_start_phys, l_runs, r_runs) = {
+        let (l_start, l_end) = l_array.get_start_end_physical_indices(len);
+        let (r_start, r_end) = r_array.get_start_end_physical_indices(len);
+        (l_start, r_start, l_end - l_start + 1, r_end - r_start + 1)
+    };
+
+    if l_runs == r_runs {
+        let physical_match = l_array.run_ends[l_start_phys..l_start_phys + l_runs - 1]
+            .iter()
+            .zip(&r_array.run_ends[r_start_phys..r_start_phys + r_runs - 1])
+            .all(|(l_re, r_re)| {
+                l_re.as_usize() - l_array.abs_start == r_re.as_usize() - r_array.abs_start
+            });
+
+        if physical_match {
+            return equal_range(
+                l_array.values,
+                r_array.values,
+                l_start_phys,
+                r_start_phys,
+                l_runs,
+            );
+        }
     }
 
-    // check run ends array are equal. The length of the physical array
-    // is used to validate the child arrays.
-    let run_ends_equal = equal_range(
-        lhs_run_ends_array,
-        rhs_run_ends_array,
-        lhs_start,
-        rhs_start,
-        lhs_run_ends_array.len(),
-    );
-
-    // if run ends array are not the same return early without validating
-    // values array.
-    if !run_ends_equal {
-        return false;
+    let mut l_phys = l_start_phys;
+    let mut r_phys = r_start_phys;
+    let mut processed = 0;
+    while processed < len {
+        if !equal_range(l_array.values, r_array.values, l_phys, r_phys, 1) {
+            return false;
+        }
+
+        let l_run_end = l_array.run_end(l_phys);
+        let r_run_end = r_array.run_end(r_phys);
+
+        let step = (l_run_end - (l_array.abs_start + processed))
+            .min(r_run_end - (r_array.abs_start + processed))
+            .min(len - processed);
+        processed += step;
+
+        if processed < len {
+            if l_array.abs_start + processed == l_run_end {
+                l_phys += 1;
+            }
+            if r_array.abs_start + processed == r_run_end {
+                r_phys += 1;
+            }
+        }

Review Comment:
   Can we explain these steps? They don't seem clearly obvious to me, especially the multiple `min`



##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,148 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: &'a [T],
+    values: &'a ArrayData,
+    abs_start: usize,
+}
 
-    if lhs.len() != rhs.len() {
-        return false;
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() >= 2,
+            "RunEndEncoded arrays are guaranteed to have at least 2 children [run_ends, values]"
+        );
+        let run_ends_data = &data.child_data()[0];
+        let run_ends = &run_ends_data.buffers()[0].typed_data::<T>()
+            [run_ends_data.offset()..run_ends_data.offset() + run_ends_data.len()];
+        let values = &data.child_data()[1];
+        Self {
+            run_ends,
+            values,
+            abs_start: data.offset() + start,
+        }
     }
 
-    let lhs_child_data = lhs.child_data();
-    let lhs_run_ends_array = &lhs_child_data[0];
-    let lhs_values_array = &lhs_child_data[1];
+    fn run_end(&self, index: usize) -> usize {
+        self.run_ends[index].as_usize()
+    }
 
-    let rhs_child_data = rhs.child_data();
-    let rhs_run_ends_array = &rhs_child_data[0];
-    let rhs_values_array = &rhs_child_data[1];
+    fn get_physical_index(&self, logical_index: usize) -> usize {
+        let logical_index = logical_index + self.abs_start;
+        if logical_index == 0 {
+            return 0;
+        }
+        match self
+            .run_ends
+            .binary_search_by(|val| val.as_usize().cmp(&logical_index))
+        {
+            Ok(idx) => idx + 1,
+            Err(idx) => idx,
+        }
+    }
 
-    if lhs_run_ends_array.len() != rhs_run_ends_array.len() {
-        return false;
+    fn get_start_end_physical_indices(&self, len: usize) -> (usize, usize) {
+        let start = self.get_physical_index(0);
+        let end = self.get_physical_index(len - 1);
+        (start, end)
     }
+}
 
-    if lhs_values_array.len() != rhs_values_array.len() {
-        return false;
+fn run_equal_inner<T: ArrowNativeType + ToPrimitive>(
+    lhs: &ArrayData,
+    rhs: &ArrayData,
+    lhs_start: usize,
+    rhs_start: usize,
+    len: usize,
+) -> bool {
+    if len == 0 {
+        return true;
+    }
+
+    let l_array = RunArrayData::<T>::new(lhs, lhs_start);
+    let r_array = RunArrayData::<T>::new(rhs, rhs_start);
+
+    let (l_start_phys, r_start_phys, l_runs, r_runs) = {
+        let (l_start, l_end) = l_array.get_start_end_physical_indices(len);
+        let (r_start, r_end) = r_array.get_start_end_physical_indices(len);
+        (l_start, r_start, l_end - l_start + 1, r_end - r_start + 1)
+    };
+
+    if l_runs == r_runs {
+        let physical_match = l_array.run_ends[l_start_phys..l_start_phys + l_runs - 1]
+            .iter()
+            .zip(&r_array.run_ends[r_start_phys..r_start_phys + r_runs - 1])
+            .all(|(l_re, r_re)| {
+                l_re.as_usize() - l_array.abs_start == r_re.as_usize() - r_array.abs_start
+            });

Review Comment:
   ```suggestion
           let l_iter = l_array.run_ends.iter().skip(l_start_phys).take(l_runs);
           let r_iter = r_array.run_ends.iter().skip(r_start_phys).take(r_runs);
           let physical_match = l_iter.zip(r_iter).all(|(l_re, r_re)| {
               l_re.as_usize() - l_array.abs_start == r_re.as_usize() - r_array.abs_start
           });
   ```
   
   It was a bit confusing to see `l_runs` calculated as `l_end - l_start + 1` but then here we essentially rebuild `l_ends` because we left it behind in the scope above. More clean this way using iterator API.
   
   Also could we leave an explanation of what this check means? `physical_match` doesn't exactly describe what check is being done here 🤔 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "manishkr (via GitHub)" <gi...@apache.org>.
manishkr commented on code in PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#discussion_r2720609708


##########
arrow-buffer/src/buffer/run.rs:
##########
@@ -199,9 +199,14 @@ where
     pub fn sliced_values(&self) -> impl Iterator<Item = E> + '_ {
         let offset = self.logical_offset;
         let len = self.logical_length;
-        let start = self.get_start_physical_index();
-        let end = self.get_end_physical_index();
-        self.run_ends[start..=end].iter().map(move |&val| {
+        let physical_slice = if len == 0 {

Review Comment:
   Done, Thanks. Also, added comment from your PR.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "vegarsti (via GitHub)" <gi...@apache.org>.
vegarsti commented on PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#issuecomment-3803672113

   > @brancz and @vegarsti -- would you also be willing to review this PR as you have worked in this area recently?
   
   For sure!


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "manishkr (via GitHub)" <gi...@apache.org>.
manishkr commented on code in PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#discussion_r2720613852


##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,122 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
 
-    if lhs.len() != rhs.len() {
-        return false;
+fn run_equal_inner<T: ArrowNativeType + ToPrimitive>(
+    lhs: &ArrayData,
+    rhs: &ArrayData,
+    lhs_start: usize,
+    rhs_start: usize,
+    len: usize,
+) -> bool {
+    if len == 0 {
+        return true;
     }
+    // RunEndEncoded arrays are guaranteed to have at least 2 children [run_ends, values]
+    let lhs_run_ends_data = &lhs.child_data()[0];

Review Comment:
   Thanks for suggestion. Refactored it.



##########
arrow-array/src/array/run_array.rs:
##########
@@ -1173,4 +1176,56 @@ mod tests {
         let values_slice2 = values_slice2.as_primitive::<Int32Type>();
         assert_eq!(values_slice2.values(), &[1]);
     }
+
+    #[test]
+    fn test_run_array_eq_diff_physical_same_logical() {

Review Comment:
   Done, Thanks.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#issuecomment-3801936313

   @brancz and @vegarsti  -- would you also be willing to review this PR as you have worked in this area recently?


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#discussion_r2711136422


##########
arrow-buffer/src/buffer/run.rs:
##########
@@ -199,9 +199,14 @@ where
     pub fn sliced_values(&self) -> impl Iterator<Item = E> + '_ {
         let offset = self.logical_offset;
         let len = self.logical_length;
-        let start = self.get_start_physical_index();
-        let end = self.get_end_physical_index();
-        self.run_ends[start..=end].iter().map(move |&val| {
+        let physical_slice = if len == 0 {

Review Comment:
   Thanks for this, I'll close my PR in favour of this (#9200)
   
   Could you add the tests I had in my PR though
   
   ```rust
   // arrow-array/src/array/run_array.rs
       #[test]
       fn test_run_array_empty() {
           let runs = new_empty_array(&DataType::Int16);
           let runs = runs.as_primitive::<Int16Type>();
           let values = new_empty_array(&DataType::Int64);
           let array = RunArray::try_new(runs, &values).unwrap();
   
           fn assertions(array: &RunArray<Int16Type>) {
               assert!(array.is_empty());
               assert_eq!(array.get_start_physical_index(), 0);
               assert_eq!(array.get_end_physical_index(), 0);
               assert!(array.get_physical_indices::<i16>(&[]).unwrap().is_empty());
               assert!(array.run_ends().is_empty());
               assert_eq!(array.run_ends().sliced_values().count(), 0);
           }
   
           assertions(&array);
           assertions(&array.slice(0, 0));
       }
   ```



##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,122 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
 
-    if lhs.len() != rhs.len() {
-        return false;
+fn run_equal_inner<T: ArrowNativeType + ToPrimitive>(
+    lhs: &ArrayData,
+    rhs: &ArrayData,
+    lhs_start: usize,
+    rhs_start: usize,
+    len: usize,
+) -> bool {
+    if len == 0 {
+        return true;
     }
+    // RunEndEncoded arrays are guaranteed to have at least 2 children [run_ends, values]
+    let lhs_run_ends_data = &lhs.child_data()[0];

Review Comment:
   There is a lot of local variables in play in this function. Can we refactor to:
   
   - Try eliminate local variables where possible (e.g. introduce small functions or blocks to clearly delineate where local variables are useful for)
   - Look into using a struct to collate the field for left vs right (e.g a struct holding `values`, `run_ends`, etc. by reference) to make it easier to read the left vs right



##########
arrow-array/src/array/run_array.rs:
##########
@@ -141,6 +141,9 @@ impl<R: RunEndIndexType> RunArray<R> {
     ///
     /// [`values`]: Self::values
     pub fn values_slice(&self) -> ArrayRef {
+        if self.len() == 0 {

Review Comment:
   Could we add a test case for this



##########
arrow-array/src/array/run_array.rs:
##########
@@ -1173,4 +1176,56 @@ mod tests {
         let values_slice2 = values_slice2.as_primitive::<Int32Type>();
         assert_eq!(values_slice2.values(), &[1]);
     }
+
+    #[test]
+    fn test_run_array_eq_diff_physical_same_logical() {

Review Comment:
   Could we also add some cases checking empty run arrays



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "manishkr (via GitHub)" <gi...@apache.org>.
manishkr commented on code in PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#discussion_r2720607716


##########
arrow-array/src/array/run_array.rs:
##########
@@ -141,6 +141,9 @@ impl<R: RunEndIndexType> RunArray<R> {
     ///
     /// [`values`]: Self::values
     pub fn values_slice(&self) -> ArrayRef {
+        if self.len() == 0 {

Review Comment:
   Done. Thanks



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#discussion_r2726355737


##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,149 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_buffer::RunEndBuffer;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: RunEndBuffer<T>,
+    values: &'a ArrayData,
+}
+
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize, len: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() == 2,
+            "RunEndEncoded arrays are guaranteed to have 2 children [run_ends, values]"
+        );
+        let run_ends_data = &data.child_data()[0];
+        let raw_run_ends_buffer = &run_ends_data.buffers()[0];
+        // SAFETY: we're reconstructing RunEndBuffer from a known valid RunArray
+        let run_ends = unsafe {
+            RunEndBuffer::<T>::new_unchecked(
+                raw_run_ends_buffer.clone().into(),
+                run_ends_data.offset() + data.offset() + start,
+                len,
+            )
+        };
 
-    if lhs.len() != rhs.len() {
-        return false;
+        let values = &data.child_data()[1];
+        Self { run_ends, values }
     }
 
-    let lhs_child_data = lhs.child_data();
-    let lhs_run_ends_array = &lhs_child_data[0];
-    let lhs_values_array = &lhs_child_data[1];
+    fn run_end(&self, index: usize) -> usize {
+        self.run_ends.values()[index].as_usize()
+    }
 
-    let rhs_child_data = rhs.child_data();
-    let rhs_run_ends_array = &rhs_child_data[0];
-    let rhs_values_array = &rhs_child_data[1];
+    fn get_start_end_physical_indices(&self) -> (usize, usize) {
+        let start = self.run_ends.get_start_physical_index();
+        let end = self.run_ends.get_end_physical_index();
+        (start, end)
+    }
+}
 
-    if lhs_run_ends_array.len() != rhs_run_ends_array.len() {
-        return false;
+fn run_equal_inner<T: ArrowNativeType + ToPrimitive>(
+    lhs: &ArrayData,
+    rhs: &ArrayData,
+    lhs_start: usize,
+    rhs_start: usize,
+    len: usize,
+) -> bool {
+    if len == 0 {
+        return true;
     }
 
-    if lhs_values_array.len() != rhs_values_array.len() {
-        return false;
+    let l_array = RunArrayData::<T>::new(lhs, lhs_start, len);
+    let r_array = RunArrayData::<T>::new(rhs, rhs_start, len);
+
+    let (l_start_phys, l_end_phys) = l_array.get_start_end_physical_indices();
+    let (r_start_phys, r_end_phys) = r_array.get_start_end_physical_indices();
+    let l_runs = l_end_phys - l_start_phys + 1;
+    let r_runs = r_end_phys - r_start_phys + 1;
+
+    if l_runs == r_runs {
+        // When the boundaries align perfectly, we don't need the complex stepping loop that calculates overlaps.
+        // Instead, we can simply treat the underlying values arrays as if they were standard primitive arrays.
+        let l_iter = l_array.run_ends.sliced_values();
+        let r_iter = r_array.run_ends.sliced_values();
+        let physical_match = l_iter.zip(r_iter).all(|(l_re, r_re)| l_re == r_re);
+
+        if physical_match {
+            // Both arrays are partitioned identically.
+            // We can just verify if the physical values in those partitions match.
+            return equal_range(
+                l_array.values,
+                r_array.values,
+                l_start_phys,
+                r_start_phys,
+                l_runs,
+            );
+        }
     }
 
-    // check run ends array are equal. The length of the physical array
-    // is used to validate the child arrays.
-    let run_ends_equal = equal_range(
-        lhs_run_ends_array,
-        rhs_run_ends_array,
-        lhs_start,
-        rhs_start,
-        lhs_run_ends_array.len(),
-    );
-
-    // if run ends array are not the same return early without validating
-    // values array.
-    if !run_ends_equal {
-        return false;
+    let mut l_phys = l_start_phys;
+    let mut r_phys = r_start_phys;
+    let mut processed = 0;
+    while processed < len {
+        if !equal_range(l_array.values, r_array.values, l_phys, r_phys, 1) {
+            return false;
+        }
+
+        let l_run_end = l_array.run_end(l_phys);
+        let r_run_end = r_array.run_end(r_phys);
+
+        //Calculate how many more logical elements are in the current run of the left and right array
+        let l_remaining_in_run = l_run_end - (l_array.run_ends.offset() + processed);
+        let r_remaining_in_run = r_run_end - (r_array.run_ends.offset() + processed);
+
+        //Calculate how many elements are left to compare in the requested range
+        let remaining_in_range = len - processed;
+
+        //Find the smallest of these three to determine our step size
+        //The goal is to move the logical cursor (processed) forward as far as possible without:
+        //Crossing the boundary of a run in the left or right array (where the value might change).
+        //Going past the total length we were asked to compare.
+        let step = l_remaining_in_run
+            .min(r_remaining_in_run)
+            .min(remaining_in_range);
+        processed += step;
+
+        if processed < len {

Review Comment:
   Can probably omit this if check? Because if `processed >= len` then next iteration will exit anyway



##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,149 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_buffer::RunEndBuffer;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: RunEndBuffer<T>,
+    values: &'a ArrayData,
+}
+
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize, len: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() == 2,
+            "RunEndEncoded arrays are guaranteed to have 2 children [run_ends, values]"
+        );
+        let run_ends_data = &data.child_data()[0];
+        let raw_run_ends_buffer = &run_ends_data.buffers()[0];
+        // SAFETY: we're reconstructing RunEndBuffer from a known valid RunArray
+        let run_ends = unsafe {
+            RunEndBuffer::<T>::new_unchecked(
+                raw_run_ends_buffer.clone().into(),
+                run_ends_data.offset() + data.offset() + start,
+                len,
+            )
+        };
 
-    if lhs.len() != rhs.len() {
-        return false;
+        let values = &data.child_data()[1];
+        Self { run_ends, values }
     }
 
-    let lhs_child_data = lhs.child_data();
-    let lhs_run_ends_array = &lhs_child_data[0];
-    let lhs_values_array = &lhs_child_data[1];
+    fn run_end(&self, index: usize) -> usize {
+        self.run_ends.values()[index].as_usize()
+    }
 
-    let rhs_child_data = rhs.child_data();
-    let rhs_run_ends_array = &rhs_child_data[0];
-    let rhs_values_array = &rhs_child_data[1];
+    fn get_start_end_physical_indices(&self) -> (usize, usize) {
+        let start = self.run_ends.get_start_physical_index();
+        let end = self.run_ends.get_end_physical_index();
+        (start, end)
+    }
+}
 
-    if lhs_run_ends_array.len() != rhs_run_ends_array.len() {
-        return false;
+fn run_equal_inner<T: ArrowNativeType + ToPrimitive>(
+    lhs: &ArrayData,
+    rhs: &ArrayData,
+    lhs_start: usize,
+    rhs_start: usize,
+    len: usize,
+) -> bool {
+    if len == 0 {
+        return true;
     }
 
-    if lhs_values_array.len() != rhs_values_array.len() {
-        return false;
+    let l_array = RunArrayData::<T>::new(lhs, lhs_start, len);
+    let r_array = RunArrayData::<T>::new(rhs, rhs_start, len);
+
+    let (l_start_phys, l_end_phys) = l_array.get_start_end_physical_indices();
+    let (r_start_phys, r_end_phys) = r_array.get_start_end_physical_indices();
+    let l_runs = l_end_phys - l_start_phys + 1;
+    let r_runs = r_end_phys - r_start_phys + 1;
+
+    if l_runs == r_runs {
+        // When the boundaries align perfectly, we don't need the complex stepping loop that calculates overlaps.

Review Comment:
   Thanks for these comments, they really helped my understanding of this code 👍 



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#issuecomment-3807907473

   Thank you @Jefffrey and @brancz 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb merged PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "manishkr (via GitHub)" <gi...@apache.org>.
manishkr commented on code in PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#discussion_r2725344711


##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,148 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: &'a [T],
+    values: &'a ArrayData,
+    abs_start: usize,
+}
 
-    if lhs.len() != rhs.len() {
-        return false;
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() >= 2,
+            "RunEndEncoded arrays are guaranteed to have at least 2 children [run_ends, values]"
+        );
+        let run_ends_data = &data.child_data()[0];
+        let run_ends = &run_ends_data.buffers()[0].typed_data::<T>()
+            [run_ends_data.offset()..run_ends_data.offset() + run_ends_data.len()];
+        let values = &data.child_data()[1];
+        Self {
+            run_ends,
+            values,
+            abs_start: data.offset() + start,
+        }
     }
 
-    let lhs_child_data = lhs.child_data();
-    let lhs_run_ends_array = &lhs_child_data[0];
-    let lhs_values_array = &lhs_child_data[1];
+    fn run_end(&self, index: usize) -> usize {
+        self.run_ends[index].as_usize()
+    }
 
-    let rhs_child_data = rhs.child_data();
-    let rhs_run_ends_array = &rhs_child_data[0];
-    let rhs_values_array = &rhs_child_data[1];
+    fn get_physical_index(&self, logical_index: usize) -> usize {
+        let logical_index = logical_index + self.abs_start;
+        if logical_index == 0 {
+            return 0;
+        }
+        match self
+            .run_ends
+            .binary_search_by(|val| val.as_usize().cmp(&logical_index))
+        {
+            Ok(idx) => idx + 1,
+            Err(idx) => idx,
+        }
+    }
 
-    if lhs_run_ends_array.len() != rhs_run_ends_array.len() {
-        return false;
+    fn get_start_end_physical_indices(&self, len: usize) -> (usize, usize) {
+        let start = self.get_physical_index(0);
+        let end = self.get_physical_index(len - 1);
+        (start, end)
     }
+}
 
-    if lhs_values_array.len() != rhs_values_array.len() {
-        return false;
+fn run_equal_inner<T: ArrowNativeType + ToPrimitive>(
+    lhs: &ArrayData,
+    rhs: &ArrayData,
+    lhs_start: usize,
+    rhs_start: usize,
+    len: usize,
+) -> bool {
+    if len == 0 {
+        return true;
+    }
+
+    let l_array = RunArrayData::<T>::new(lhs, lhs_start);
+    let r_array = RunArrayData::<T>::new(rhs, rhs_start);
+
+    let (l_start_phys, r_start_phys, l_runs, r_runs) = {
+        let (l_start, l_end) = l_array.get_start_end_physical_indices(len);
+        let (r_start, r_end) = r_array.get_start_end_physical_indices(len);
+        (l_start, r_start, l_end - l_start + 1, r_end - r_start + 1)
+    };
+
+    if l_runs == r_runs {
+        let physical_match = l_array.run_ends[l_start_phys..l_start_phys + l_runs - 1]
+            .iter()
+            .zip(&r_array.run_ends[r_start_phys..r_start_phys + r_runs - 1])
+            .all(|(l_re, r_re)| {
+                l_re.as_usize() - l_array.abs_start == r_re.as_usize() - r_array.abs_start
+            });

Review Comment:
   Changed it accordingly RunEndBuffer related struct changes. Thanks



##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,148 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: &'a [T],
+    values: &'a ArrayData,
+    abs_start: usize,
+}
 
-    if lhs.len() != rhs.len() {
-        return false;
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() >= 2,
+            "RunEndEncoded arrays are guaranteed to have at least 2 children [run_ends, values]"
+        );
+        let run_ends_data = &data.child_data()[0];
+        let run_ends = &run_ends_data.buffers()[0].typed_data::<T>()

Review Comment:
   Changed. Thanks



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "manishkr (via GitHub)" <gi...@apache.org>.
manishkr commented on code in PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#discussion_r2725348529


##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,148 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: &'a [T],
+    values: &'a ArrayData,
+    abs_start: usize,
+}
 
-    if lhs.len() != rhs.len() {
-        return false;
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() >= 2,
+            "RunEndEncoded arrays are guaranteed to have at least 2 children [run_ends, values]"
+        );
+        let run_ends_data = &data.child_data()[0];
+        let run_ends = &run_ends_data.buffers()[0].typed_data::<T>()
+            [run_ends_data.offset()..run_ends_data.offset() + run_ends_data.len()];
+        let values = &data.child_data()[1];
+        Self {
+            run_ends,
+            values,
+            abs_start: data.offset() + start,
+        }
     }
 
-    let lhs_child_data = lhs.child_data();
-    let lhs_run_ends_array = &lhs_child_data[0];
-    let lhs_values_array = &lhs_child_data[1];
+    fn run_end(&self, index: usize) -> usize {
+        self.run_ends[index].as_usize()
+    }
 
-    let rhs_child_data = rhs.child_data();
-    let rhs_run_ends_array = &rhs_child_data[0];
-    let rhs_values_array = &rhs_child_data[1];
+    fn get_physical_index(&self, logical_index: usize) -> usize {
+        let logical_index = logical_index + self.abs_start;
+        if logical_index == 0 {
+            return 0;
+        }
+        match self
+            .run_ends
+            .binary_search_by(|val| val.as_usize().cmp(&logical_index))
+        {
+            Ok(idx) => idx + 1,
+            Err(idx) => idx,
+        }
+    }
 
-    if lhs_run_ends_array.len() != rhs_run_ends_array.len() {
-        return false;
+    fn get_start_end_physical_indices(&self, len: usize) -> (usize, usize) {
+        let start = self.get_physical_index(0);
+        let end = self.get_physical_index(len - 1);
+        (start, end)
     }
+}
 
-    if lhs_values_array.len() != rhs_values_array.len() {
-        return false;
+fn run_equal_inner<T: ArrowNativeType + ToPrimitive>(
+    lhs: &ArrayData,
+    rhs: &ArrayData,
+    lhs_start: usize,
+    rhs_start: usize,
+    len: usize,
+) -> bool {
+    if len == 0 {
+        return true;
+    }
+
+    let l_array = RunArrayData::<T>::new(lhs, lhs_start);
+    let r_array = RunArrayData::<T>::new(rhs, rhs_start);
+
+    let (l_start_phys, r_start_phys, l_runs, r_runs) = {
+        let (l_start, l_end) = l_array.get_start_end_physical_indices(len);
+        let (r_start, r_end) = r_array.get_start_end_physical_indices(len);
+        (l_start, r_start, l_end - l_start + 1, r_end - r_start + 1)
+    };
+
+    if l_runs == r_runs {
+        let physical_match = l_array.run_ends[l_start_phys..l_start_phys + l_runs - 1]
+            .iter()
+            .zip(&r_array.run_ends[r_start_phys..r_start_phys + r_runs - 1])
+            .all(|(l_re, r_re)| {
+                l_re.as_usize() - l_array.abs_start == r_re.as_usize() - r_array.abs_start
+            });
+
+        if physical_match {
+            return equal_range(
+                l_array.values,
+                r_array.values,
+                l_start_phys,
+                r_start_phys,
+                l_runs,
+            );
+        }
     }
 
-    // check run ends array are equal. The length of the physical array
-    // is used to validate the child arrays.
-    let run_ends_equal = equal_range(
-        lhs_run_ends_array,
-        rhs_run_ends_array,
-        lhs_start,
-        rhs_start,
-        lhs_run_ends_array.len(),
-    );
-
-    // if run ends array are not the same return early without validating
-    // values array.
-    if !run_ends_equal {
-        return false;
+    let mut l_phys = l_start_phys;
+    let mut r_phys = r_start_phys;
+    let mut processed = 0;
+    while processed < len {
+        if !equal_range(l_array.values, r_array.values, l_phys, r_phys, 1) {
+            return false;
+        }
+
+        let l_run_end = l_array.run_end(l_phys);
+        let r_run_end = r_array.run_end(r_phys);
+
+        let step = (l_run_end - (l_array.abs_start + processed))
+            .min(r_run_end - (r_array.abs_start + processed))
+            .min(len - processed);
+        processed += step;
+
+        if processed < len {
+            if l_array.abs_start + processed == l_run_end {
+                l_phys += 1;
+            }
+            if r_array.abs_start + processed == r_run_end {
+                r_phys += 1;
+            }
+        }

Review Comment:
   Added comment to explain it. Basically it's finding minimum chunk of sub-array that can be compared in equal_range, do you have any other idea in mind? Thanks.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "manishkr (via GitHub)" <gi...@apache.org>.
manishkr commented on code in PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#discussion_r2726948727


##########
arrow-data/src/equal/run.rs:
##########
@@ -16,71 +16,149 @@
 // under the License.
 
 use crate::data::ArrayData;
+use arrow_buffer::ArrowNativeType;
+use arrow_buffer::RunEndBuffer;
+use arrow_schema::DataType;
+use num_traits::ToPrimitive;
 
 use super::equal_range;
 
-/// The current implementation of comparison of run array support physical comparison.
-/// Comparing run encoded array based on logical indices (`lhs_start`, `rhs_start`) will
-/// be time consuming as converting from logical index to physical index cannot be done
-/// in constant time. The current comparison compares the underlying physical arrays.
+/// Returns true if the two `RunEndEncoded` arrays are equal.
+///
+/// This provides a specialized implementation of equality for REE arrays that
+/// handles differences in run-encoding by iterating through the logical range.
 pub(super) fn run_equal(
     lhs: &ArrayData,
     rhs: &ArrayData,
     lhs_start: usize,
     rhs_start: usize,
     len: usize,
 ) -> bool {
-    if lhs_start != 0
-        || rhs_start != 0
-        || (lhs.len() != len && rhs.len() != len)
-        || lhs.offset() > 0
-        || rhs.offset() > 0
-    {
-        unimplemented!("Logical comparison for run array not supported.")
+    let lhs_index_type = match lhs.data_type() {
+        DataType::RunEndEncoded(f, _) => f.data_type(),
+        _ => unreachable!(),
+    };
+
+    match lhs_index_type {
+        DataType::Int16 => run_equal_inner::<i16>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int32 => run_equal_inner::<i32>(lhs, rhs, lhs_start, rhs_start, len),
+        DataType::Int64 => run_equal_inner::<i64>(lhs, rhs, lhs_start, rhs_start, len),
+        _ => unreachable!(),
     }
+}
+
+struct RunArrayData<'a, T: ArrowNativeType> {
+    run_ends: RunEndBuffer<T>,
+    values: &'a ArrayData,
+}
+
+impl<'a, T: ArrowNativeType + ToPrimitive> RunArrayData<'a, T> {
+    fn new(data: &'a ArrayData, start: usize, len: usize) -> Self {
+        debug_assert!(
+            data.child_data().len() == 2,
+            "RunEndEncoded arrays are guaranteed to have 2 children [run_ends, values]"
+        );
+        let run_ends_data = &data.child_data()[0];
+        let raw_run_ends_buffer = &run_ends_data.buffers()[0];
+        // SAFETY: we're reconstructing RunEndBuffer from a known valid RunArray
+        let run_ends = unsafe {
+            RunEndBuffer::<T>::new_unchecked(
+                raw_run_ends_buffer.clone().into(),
+                run_ends_data.offset() + data.offset() + start,
+                len,
+            )
+        };
 
-    if lhs.len() != rhs.len() {
-        return false;
+        let values = &data.child_data()[1];
+        Self { run_ends, values }
     }
 
-    let lhs_child_data = lhs.child_data();
-    let lhs_run_ends_array = &lhs_child_data[0];
-    let lhs_values_array = &lhs_child_data[1];
+    fn run_end(&self, index: usize) -> usize {
+        self.run_ends.values()[index].as_usize()
+    }
 
-    let rhs_child_data = rhs.child_data();
-    let rhs_run_ends_array = &rhs_child_data[0];
-    let rhs_values_array = &rhs_child_data[1];
+    fn get_start_end_physical_indices(&self) -> (usize, usize) {
+        let start = self.run_ends.get_start_physical_index();
+        let end = self.run_ends.get_end_physical_index();
+        (start, end)
+    }
+}
 
-    if lhs_run_ends_array.len() != rhs_run_ends_array.len() {
-        return false;
+fn run_equal_inner<T: ArrowNativeType + ToPrimitive>(
+    lhs: &ArrayData,
+    rhs: &ArrayData,
+    lhs_start: usize,
+    rhs_start: usize,
+    len: usize,
+) -> bool {
+    if len == 0 {
+        return true;
     }
 
-    if lhs_values_array.len() != rhs_values_array.len() {
-        return false;
+    let l_array = RunArrayData::<T>::new(lhs, lhs_start, len);
+    let r_array = RunArrayData::<T>::new(rhs, rhs_start, len);
+
+    let (l_start_phys, l_end_phys) = l_array.get_start_end_physical_indices();
+    let (r_start_phys, r_end_phys) = r_array.get_start_end_physical_indices();
+    let l_runs = l_end_phys - l_start_phys + 1;
+    let r_runs = r_end_phys - r_start_phys + 1;
+
+    if l_runs == r_runs {
+        // When the boundaries align perfectly, we don't need the complex stepping loop that calculates overlaps.
+        // Instead, we can simply treat the underlying values arrays as if they were standard primitive arrays.
+        let l_iter = l_array.run_ends.sliced_values();
+        let r_iter = r_array.run_ends.sliced_values();
+        let physical_match = l_iter.zip(r_iter).all(|(l_re, r_re)| l_re == r_re);
+
+        if physical_match {
+            // Both arrays are partitioned identically.
+            // We can just verify if the physical values in those partitions match.
+            return equal_range(
+                l_array.values,
+                r_array.values,
+                l_start_phys,
+                r_start_phys,
+                l_runs,
+            );
+        }
     }
 
-    // check run ends array are equal. The length of the physical array
-    // is used to validate the child arrays.
-    let run_ends_equal = equal_range(
-        lhs_run_ends_array,
-        rhs_run_ends_array,
-        lhs_start,
-        rhs_start,
-        lhs_run_ends_array.len(),
-    );
-
-    // if run ends array are not the same return early without validating
-    // values array.
-    if !run_ends_equal {
-        return false;
+    let mut l_phys = l_start_phys;
+    let mut r_phys = r_start_phys;
+    let mut processed = 0;
+    while processed < len {
+        if !equal_range(l_array.values, r_array.values, l_phys, r_phys, 1) {
+            return false;
+        }
+
+        let l_run_end = l_array.run_end(l_phys);
+        let r_run_end = r_array.run_end(r_phys);
+
+        //Calculate how many more logical elements are in the current run of the left and right array
+        let l_remaining_in_run = l_run_end - (l_array.run_ends.offset() + processed);
+        let r_remaining_in_run = r_run_end - (r_array.run_ends.offset() + processed);
+
+        //Calculate how many elements are left to compare in the requested range
+        let remaining_in_range = len - processed;
+
+        //Find the smallest of these three to determine our step size
+        //The goal is to move the logical cursor (processed) forward as far as possible without:
+        //Crossing the boundary of a run in the left or right array (where the value might change).
+        //Going past the total length we were asked to compare.
+        let step = l_remaining_in_run
+            .min(r_remaining_in_run)
+            .min(remaining_in_range);
+        processed += step;
+
+        if processed < len {

Review Comment:
   Done, Thanks.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: [9018]Fixed RunArray slice offsets(row, cast, eq) [arrow-rs]

Posted by "vegarsti (via GitHub)" <gi...@apache.org>.
vegarsti commented on PR #9213:
URL: https://github.com/apache/arrow-rs/pull/9213#issuecomment-3839922881

   Sorry for not reviewing in time! Please don't give up on tagging me! 😄 


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org